nodejs 从绝对路径获取文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19811541/
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
nodejs get file name from absolute path?
提问by fxp
If there any API could retrieve file name from an absolute file path?
如果有任何 API 可以从绝对文件路径中检索文件名?
e.g. "foo.txt"from "/var/www/foo.txt"
例如"foo.txt"来自"/var/www/foo.txt"
I know it works with string operation, like fullpath.replace(/.+\//, '')but I want to know is there a more 'formal' way, like file.getName()in java, could do it.
我知道它适用于字符串操作,fullpath.replace(/.+\//, '')但我想知道是否有更“正式”的方式,比如file.getName()在 Java 中,可以做到这一点。
NodeJS get file name from absolute path?
NodeJS从绝对路径获取文件名?
回答by Victor Stanciu
回答by Rubin bhandari
To get the file name portion of the file name, the basename method is used:
要获取文件名的文件名部分,使用 basename 方法:
var path = require("path");
var fileName = "C:\Python27\ArcGIS10.2\python.exe";
var file = path.basename(fileName);
console.log(file); // 'python.exe'
If you want the file name without the extension, you can pass the extension variable (containing the extension name) to the basename method telling Node to return only the name without the extension:
如果你想要没有扩展名的文件名,你可以将扩展名变量(包含扩展名)传递给 basename 方法,告诉 Node 只返回没有扩展名的名称:
var path = require("path");
var fileName = "C:\Python27\ArcGIS10.2\python.exe";
var extension = path.extname(fileName);
var file = path.basename(fileName,extension);
console.log(file); // 'python'
回答by Tigertron
For those interested in removing extension from filename, you can use https://nodejs.org/api/path.html#path_path_basename_path_ext
对于那些有兴趣从文件名中删除扩展名的人,您可以使用 https://nodejs.org/api/path.html#path_path_basename_path_ext
path.basename('/foo/bar/baz/asdf/quux.html', '.html');
回答by leo
If you already know that the path separator is /(i.e. you are writing for a specific platform/environment), as implied by the example in your question, you could keep it simple and split the string by separator:
如果您已经知道路径分隔符是/(即您正在为特定平台/环境编写),正如您问题中的示例所暗示的那样,您可以保持简单并按分隔符拆分字符串:
'/foo/bar/baz/asdf/quux.html'.split('/').pop()
That would be faster(and cleaner imo) than replacing by regular expression.
这比用正则表达式替换更快(更干净)。
Again: Only do this if you're writing for a specific environment, otherwise use the pathmodule, as paths are surprisingly complex. Windows, for instance, supports /in many cases but notfor e.g. the \\?\?style prefixes used for shared network folders and the like. On Windows the above method is doomed to fail, sooner or later.
再次:只有在为特定环境编写时才这样做,否则使用path模块,因为路径非常复杂。Windows中,例如,支持/在许多情况下,但不是EG的\\?\?用于共享网络文件夹和类似风格的前缀。在 Windows 上,上述方法迟早是注定要失败的。
回答by Kevin Muchwat
var path = require("path");
var filepath = "C:\Python27\ArcGIS10.2\python.exe";
var name = path.parse(filepath).name;
Gives you the name of the file without extension, if you need the name with extention use
为您提供不带扩展名的文件名,如果您需要带扩展名的名称,请使用
var path = require("path");
var filepath = "C:\Python27\ArcGIS10.2\python.exe";
var name = path.basename(filepath);
回答by Visv M
In NodeJS, __filename.split(/\|//).pop() returns just the file name from the absolute file path on any OS platform. Why need to care about remembering/importing an API while this regex approach also letting us recollect our regex skills.
在 NodeJS 中, __filename.split(/\|//).pop() 仅返回来自任何操作系统平台上绝对文件路径的文件名。为什么需要关心记住/导入 API 而这种正则表达式方法也让我们回忆我们的正则表达式技能。
回答by Joey587
So Nodejs comes with the default global variable called '__fileName'that holds the current file being executed
My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic
所以 Nodejs 附带了一个默认的全局变量,称为 '__fileName'保存正在执行的当前文件我的建议是将 __fileName 从任何文件传递给服务,以便文件名的检索是动态的
Below, I make use of the fileName string and then split it based on the path.sep. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.
下面,我使用 fileName 字符串,然后根据path.sep. 注意 path.sep 避免了 posix 文件分隔符和 windows 文件分隔符的问题('/' 和 '\' 的问题)。它干净多了。获取子字符串并仅获取最后一个分隔的名称并将其与实际长度相减 3 不言而喻。
You can write a service like this (Note this is in typescript , but you can very well write it in js )
您可以编写这样的服务(注意这是在 typescript 中,但您可以很好地在 js 中编写)
export class AppLoggingConstants {
constructor(){
}
// Here make sure the fileName param is actually '__fileName'
getDefaultMedata(fileName: string, methodName: string) {
const appName = APP_NAME;
const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
//const actualFileName = fileName;
return appName+ ' -- '+actualFileName;
}
}
export const AppLoggingConstantsInstance = new AppLoggingConstants();

