在我的node.js应用程序中,我有可以传递的函数
操作系统风格的路径,例如c:\ my\docs\mydoc.doc(或/usr/docs/mydoc.doc或其他什么是本地的)
文件URL,例如file:// c:/my/docs/mydoc.doc(我不确定'\'的有效性?)
无论哪种方式,我需要检查它们是否引用一个特定的位置,它将始终作为本地OS风格的路径存在,例如c:\ mydata\directory \或/ usr/mydata /目录
显然对于OS风格的路径我可以将它们比作字符串 - 它们应该总是相同(它们是用路径创建的)但是FILE:// URLS不一定使用path.sep,因此不会"字符串匹配" "?
关于处理这个的最佳方法的任何建议(我个人试图通过任何一种或多种斜线打破一切,然后检查每一块?
小智 7
我将发布自己对此的看法 - 因为它来自我从Facebook上的某个人那里得到的建议(不是 - 真的!)并且它以某种方式使用路径 - 它可能不是为了 - 例如我不是确定这是正确的"解决方案" - 我不确定我是不是在开发路径.
Facebook的提示是,路径实际上只是一个用"/"和"\"分隔符处理字符串的实用程序 - 它忽略了其他所有内容 - 根本不关心那里的内容.
在此基础上,我们可以使用
path.normalize(ourpath)
Run Code Online (Sandbox Code Playgroud)
这将把所有分隔符转换为本地操作系统首选的(path.sep)
这意味着它们将匹配我的OS风格的目录(也是用路径制作),所以我可以比较那些 - 而不需要手动去掉斜线...
例如
之前
file://awkward/use/of\\slashes\in/this/path
Run Code Online (Sandbox Code Playgroud)
后
file:\awkward\use\of\slashes\in\this\path (Windows)
Run Code Online (Sandbox Code Playgroud)
要么
file:/awkward/use/of/slashes/in/this/path (everywhere else)
Run Code Online (Sandbox Code Playgroud)
删除file://之前(或file:+ path.sep之后)=本地操作系统风格的路径!?
只需对字符串进行一些操作并检查以确保在纠正差异后它们是相同的:
var path = require('path');
var pathname = "\\usr\\home\\newbeb01\\Desktop\\testinput.txt";
var pathname2 = "file://usr/home/newbeb01/Desktop/testinput.txt"
if(PreparePathNameForComparing(pathname) == PreparePathNameForComparing(pathname2))
{ console.log("Same path"); }
else
{ console.log("Not the same path"); }
function PreparePathNameForComparing(pathname)
{
var returnString = pathname;
//try to find the file uri prefix, if there strip it off
if(pathname.search("file://") != -1 || pathname.search("FILE://") != -1)
{ returnString = pathname.substring(6, pathname.length); }
//now make all slashes the same
if(path.sep === '\\') //replace all '/' with '\\'
{ returnString = returnString.replace(/\//g, '\\'); }
else //replace all '\\' with '/'
{ returnString = returnString.replace(/\\/g, '/'); }
return returnString;
}
Run Code Online (Sandbox Code Playgroud)
我检查了 URI 路径名称指示符“file://”是否存在,如果存在,我将其从比较字符串中删除。然后我根据模块会给我的路径分隔符节点进行归一化。这样它就可以在 Linux 或 Windows 环境中工作。
| 归档时间: |
|
| 查看次数: |
4024 次 |
| 最近记录: |