Nodejs中如何从绝对路径获取文件名?
例如
"foo.txt"
来自 "/var/www/foo.txt"
我知道它适用于字符串操作,例如
fullpath.replace(/.+\//, '')
,
但我想知道是否有一种明确的方法,例如Java中的file.getName()
?
使用
basename
模块的path
方法:
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
这里是上面示例的文档。
要获取文件名的文件名部分,使用basename方法:
var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);
console.log(file); // 'python.exe'
如果您想要不带扩展名的文件名,可以将扩展变量(包含扩展名)传递给 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'
var path = require("path");
var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
var name = path.parse(filepath).name;
console.log("name:", name); // Output: python
var base = path.parse(filepath).base;
console.log("base:", base); // Output: python.exe
var ext = path.parse(filepath).ext;
console.log("ext:", ext); // Output: .exe
var dir = path.parse(filepath).dir;
console.log("dir:", dir); // Output: C:\Python27\ArcGIS10.2
var root = path.parse(filepath).root;
console.log("root:", root); // Output: C:\
或
const path = require("path");
const filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";
const { name, base, ext, dir, root } = path.parse(filepath);
console.log(`Name: ${name}\nBase: ${base}\nExtension: ${ext}\nDirectory: ${dir}\nRoot: ${root}`);
对于那些有兴趣从文件名中删除扩展名的人,您可以使用 https://nodejs.org/api/path.html#path_path_basename_path_ext
path.basename('/foo/bar/baz/asdf/quux.html', '.html');
path
是
nodeJS module
意味着您无需安装任何软件包即可使用其属性。import path from 'path'
const dir_name = path.basename('/Users/Project_naptha/demo_path.js')
console.log(dir_name)
// returns
demo_path.js
示例代码:
const path = require('path');
const absolutePath = '/var/www/foo.txt';
const fileName = path.basename(absolutePath);
console.log(fileName); // Output: foo.txt
path.basename()函数会自动从给定路径中提取文件名
'__fileName'
的默认全局变量,它保存当前正在执行的文件 我的建议是将 __fileName 从任何文件传递给服务,以便动态检索文件名
下面,我使用 fileName 字符串,然后根据
path.sep
对其进行拆分。注意 path.sep 避免了 posix 文件分隔符和 windows 文件分隔符的问题(“/”和“\”的问题)。它干净得多。获取子字符串并仅获取最后一个分隔名称,然后用实际长度减去 3 就可以说明问题了。
你可以编写这样的服务(注意这是用 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();