Javascript 从文件路径或 url 获取目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29496515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get directory from a file path or url
提问by Get Off My Lawn
I am trying to get the directory location of a file, and I'm not sure how to get it. I can't seem to find a module that allows me to do this.
我正在尝试获取文件的目录位置,但我不确定如何获取它。我似乎找不到允许我这样做的模块。
So for example say I have this string:
因此,例如说我有这个字符串:
/this/is/a/path/to/a/file.html
how can I get this:
我怎么能得到这个:
/this/is/a/path/to/a
I know I can use something like this:
我知道我可以使用这样的东西:
path.substr(0, path.lastIndexOf("/") - 1);
But I am not sure if that is as good of a method as something that might be built in to node.
但我不确定这是否与可能内置到 node.js 的方法一样好。
I have also tried:
我也试过:
var info = url.parse(full_path);
console.log(info);
and the result doesn't return what I am looking for, that gets the full path including the filename.
结果没有返回我正在寻找的内容,它获取包括文件名的完整路径。
So, is there something built into node that can do this and do it well?
那么,节点中是否有内置的东西可以做到这一点并且做得很好?
回答by Hypaethral
回答by cronoklee
Using plain JS, this will work:
使用普通的 JS,这将起作用:
var e = '/this/is/a/path/to/a/file.html'
e.split("/").slice(0,-1).join("/") //split to array & remove last element
//result: '/this/is/a/path/to/a'
OR...if you prefer a one liner (using regex):
或者...如果您更喜欢单衬(使用正则表达式):
"/this/is/a/path/to/a/file.html".replace(/(.*?)[^/]*\..*$/,'')
//result: '/this/is/a/path/to/a/'
OR...finally, the good old fashioned (and faster):
或者......最后,老式的(更快):
var e = '/this/is/a/path/to/a/file.html'
e.substr(0, e.lastIndexOf("/"))
//result: '/this/is/a/path/to/a'
回答by Jon Carter
I think you're looking for path.dirname
我想你正在寻找 path.dirname
回答by Ulad Kasach
filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
- split string into array delimited by "/"
- drop the last element of the array (which would be the file name + extension)
- join the array w/ "/" to generate the directory path
- 将字符串拆分为以“/”分隔的数组
- 删除数组的最后一个元素(这将是文件名 + 扩展名)
- 加入带有“/”的数组以生成目录路径
回答by sebnukem
Have you tried the dirnamefunction of the pathmodule: https://nodejs.org/api/path.html#path_path_dirname_p
有没有试过模块的dirname功能path: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'
回答by Stefan Steiger
For plain JavaScript, this will work:
对于纯 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)

