NODE.JS-如何处理OS和URL样式的“路径"的混合正确吗? [英] NODE.JS - how to handle a mix of OS and URL-style "paths" correctly?
问题描述
在我的node.js应用程序中,我有可以传递的功能
In my node.js app I have functions which can be passed either
OS样式的路径,例如c:\ my \ docs \ mydoc.doc(或/usr/docs/mydoc.doc或任何本地文件)
OS-style paths e.g. c:\my\docs\mydoc.doc (or /usr/docs/mydoc.doc or whatever is local)
文件网址,例如file://c:/my/docs/mydoc.doc(我不确定'\'s in ??的有效性?)
File URLS e.g. file://c:/my/docs/mydoc.doc (which I'm not sure about the validity of '\'s in??)
无论哪种方式,我都需要检查它们是否引用了一个特定的位置,该位置将始终作为本地OS样式路径存在,例如c:\ mydata \ directory \或/usr/mydata/directory
Either way, I need to check to see if they refer to a specific location which will always exist as a local OS-style path e.g. c:\mydata\directory\ or /usr/mydata/directory
显然,对于OS风格的路径,我可以将它们作为字符串进行比较-它们应该始终相同(它们是使用path创建的),但是FILE://URL不一定要使用path.sep,因此不会字符串匹配"?
Obviously for OS-style paths I can just compare them as strings - they SHOULD always be the same (they're created with path) but FILE:// URLS don't necessarily use path.sep and so won't "string match"?
关于处理此问题的最佳方法的任何建议(我个人倾向于用任何一种或多种斜杠来打破一切,然后检查每件??
Any suggestions as to the best way to handle this (I'm personally tempted to break EVERYTHING by one-or-more slashes of either sort and then check each piece??
推荐答案
只需对字符串进行一些处理,并在校正差异后检查以确保它们相同:
Just do some manipulation of the string and check to make sure they are the same after correcting for the differences:
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环境中工作.
I checked to see if the URI path name indicator "file://" was there, if so, I deleted it off my compare string. Then I normalized based on the path separator node path module will give me. This way it should work in either Linux or Windows environment.
这篇关于NODE.JS-如何处理OS和URL样式的“路径"的混合正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!