如果有任何API可以从绝对文件路径中检索文件名?
例如"foo.txt"来自"/var/www/foo.txt"
我知道它适用于字符串操作,fullpath.replace(/.+\//, '')
但我想知道是否有一种更"正式"的方式,就像file.getName()在java中一样,可以做到.
NodeJS从绝对路径获取文件名?
Vic*_*ciu 490
使用模块的basename方法path:
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
Run Code Online (Sandbox Code Playgroud)
以下是上述示例的文档.
小智 29
要获取文件名的文件名部分,请使用basename方法:
var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);
console.log(file); // 'python.exe'
Run Code Online (Sandbox Code Playgroud)
的console.log(文件); 如果您想要没有扩展名的文件名,可以将扩展变量(包含扩展名)传递给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'
Run Code Online (Sandbox Code Playgroud)
小智 13
对于那些有兴趣从文件名中删除扩展名的人,您可以使用 https://nodejs.org/api/path.html#path_path_basename_path_ext
path.basename('/foo/bar/baz/asdf/quux.html', '.html');
Run Code Online (Sandbox Code Playgroud)
var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.parse(filepath).name;
// returns
'python'
Run Code Online (Sandbox Code Playgroud)
上面的代码返回没有扩展名的文件名,如果你需要带扩展名的名称使用
var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.basename(filepath);
// returns
'python.exe'
Run Code Online (Sandbox Code Playgroud)
如果您已经知道路径分隔符/(即您正在为特定平台/环境编写),如问题中的示例所示,您可以保持简单并按分隔符拆分字符串:
'/foo/bar/baz/asdf/quux.html'.split('/').pop()
Run Code Online (Sandbox Code Playgroud)
这比用正则表达式替换更快(而且更干净)。
再次强调:仅当您为特定环境编写时才执行此操作,否则请使用该path模块,因为路径非常复杂。例如,Windows/在许多情况下支持,但不支持\\?\?用于共享网络文件夹等的样式前缀。在 Windows 上,上述方法迟早会失败。