从文件path或url获取目录

我正在尝试获取文件的目录位置,我不知道如何获取它。 我似乎无法find一个模块,允许我这样做。

所以例如说我有这个string:

/this/is/a/path/to/a/file.html 

我怎么能得到这个:

 /this/is/a/path/to/a 

我知道我可以使用这样的东西:

 path.substr(0, path.lastIndexOf("/") - 1); 

但是我不确定这是否像一个可能内置于节点的方法一样好。

我也试过了:

 var info = url.parse(full_path); console.log(info); 

结果不会返回我正在寻找的,这将得到包括文件名的完整path。

那么,有没有内build的节点可以做到这一点,做得好呢?

使用node.js的path模块:

 path.dirname('/this/is/a/path/to/a/file'); 

回报

 '/this/is/a/path/to/a' 

使用普通的JS,这将工作:

 var e = '/this/is/a/path/to/a/file.html' e = e.split('/') //break the string into an array e.pop() //remove its last element e= e.join('/') //join the array back into a string //result: '/this/is/a/path/to/a' 

或者…如果你喜欢一个class轮(使用正则expression式):

 "/this/is/a/path/to/a/file.html".replace(/(.*?)[^/]*\..*$/,'$1') //result: '/this/is/a/path/to/a/' 

或者…最后,好老式(更快):

 var e = '/this/is/a/path/to/a/file.html' e.substr(0, e.lastIndexOf("/")) //result: '/this/is/a/path/to/a' 

我想你正在寻找path.dirname

您是否尝试过path模块的dirnamefunction: https : //nodejs.org/api/path.html#path_path_dirname_p

 path.dirname('/this/is/a/path/to/a/file.html') // returns '/this/is/a/path/to/a' 

对于普通的JavaScript,这将工作:

 function getDirName(e) { if(e === null) return '/'; if(e.indexOf("/") !== -1) { e = e.split('/') //break the string into an array e.pop() //remove its last element e= e.join('/') //join the array back into a string if(e === '') return '/'; return e; } return "/"; } var e = '/this/is/a/path/to/a/file.html' var e = 'file.html' var e = '/file.html' getDirName(e)