NODE.JS – 如何正确处理操作系统和URL风格的“path”混合?

在我的node.js应用程序中,我有可以传递的函数

OS风格的path,例如c:\ my \ docs \ mydoc.doc(或者/usr/docs/mydoc.doc或者其他什么都是本地的)

文件URL例如file:// c:/my/docs/mydoc.doc(我不确定'\'的有效性在??中)

无论哪种方式,我需要检查它们是否指向一个特定的位置,这个位置总是以本地OS样式的path存在,例如c:\ mydata \ directory \或/ usr / mydata /目录

显然,对于OS风格的path,我可以将它们作为string进行比较 – 它们应该总是相同的(它们是用path创build的),但FILE:// URL不一定使用path.sep,所以不会使用“string match “?

任何build议,以最好的方式来处理(我个人试图打破所有的一个或多个斜线,然后检查每一个?

只要对string进行一些操作,并在纠正差异后检查它们是否相同:

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; } 

我检查了URIpath名称指示符“file://”是否存在,如果是的话,我把它从我的比较string中删除。 然后,我基于path分隔符节点path模块归一化将给我。 这样它可以在Linux或Windows环境下工作。

我要发表自己的看法 – 因为它来自我从Facebook上的某个人那里得到的build议(不是真的!),它以某种可能不适合的方式使用了path – 例如,我不是肯定这是正确的“解决scheme” – 我不知道我不是在开发path。

Facebook的提示是,path实际上只是一个用“/”和“\”分隔符处理string的工具 – 它忽略了其他所有内容 – 根本不关心那里的内容。

在此基础上,我们可以使用

 path.normalize(ourpath) 

将所有分隔符转换为本地操作系统首选( path.sep

这意味着他们将匹配我的操作系统风格的目录(这也是path),所以我可以比较这些 – 不诉诸手动切出斜杠…

例如

之前

 file://awkward/use/of\\slashes\in/this/path 

 file:\awkward\use\of\slashes\in\this\path (Windows) 

要么

 file:/awkward/use/of/slashes/in/this/path (everywhere else) 

删除file://之前(或file: + path.sep之后)=本地OS样式的path!