NODE.JS - 如何正确处理操作系统和URL样式"paths"的混合?



在我的node.js应用程序中,我有一些函数可以通过

操作系统风格的路径,例如c:\my\docs\mydoc.doc(或/usr/docs/mydoc.doc或任何本地路径)

文件URLS,例如File://c:/my/docs/mydoc.doc(我不确定"\’s in?"的有效性)

无论哪种方式,我都需要检查它们是否引用了一个特定的位置,该位置将始终作为本地操作系统样式的路径存在,例如c:\mydata\directory\或/usr/mydata/directory

显然,对于操作系统风格的路径,我可以将它们作为字符串进行比较——它们应该总是相同的(它们是用路径创建的),但FILE://URLS不一定使用path.sep,所以不会"字符串匹配"吗?

关于处理这件事的最佳方法,有什么建议吗?(我个人很想用一个或多个任意类型的斜杠来打破一切,然后检查每一块??

我将发表我自己对此的看法,因为这是我从Facebook上的某个人那里得到的建议(不,真的!),它使用路径的方式可能不是它想要的——例如,我不确定这是正确的"解决方案"——我不确定我没有利用路径。

Facebook的提示是,path实际上只是一个用于处理带有"/"one_answers"\"分隔符的字符串的实用程序,它忽略了其他所有内容,根本不在乎里面有什么。

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

path.normalize(ourpath)

它将把所有分离器转换为本地操作系统首选分离器(path.sep

这意味着它们将与我的操作系统风格目录(也有路径)相匹配,所以我可以比较它们,而无需手动删除斜杠。。。

例如

之前

file://awkward/use/of\slashesin/this/path

之后

file:awkwarduseofslashesinthispath (Windows)

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

删除之前的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;
}

我检查了一下URI路径名指示符"file://"是否存在,如果存在,我将其从比较字符串中删除。然后我规范化了基于路径分隔符的节点路径模块会给我。这样它应该在Linux或Windows环境中工作。

最新更新