如何从Nodejs中的绝对路径获取文件名?

如。“/var/www/foo.txt”中的foo.txt

我知道它适用于字符串操作,如fullpath.replace(/。+\//, ''), 但我想知道是否有显式的方法,如Java中的file.getName() ?


当前回答

var path = require("path");

var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";

var name = path.parse(filepath).name;
console.log(name); //python

var base = path.parse(filepath).base;
console.log(base); //python.exe

var ext = path.parse(filepath).ext;
console.log(ext); //.exe

其他回答

在NodeJS中,__filename.split(/\|//).pop()只返回任何OS平台上绝对文件路径中的文件名。 为什么要关心记住/导入API,而这种正则表达式方法也让我们回忆起我们的正则表达式技能。

对于那些有兴趣从文件名中删除扩展名的人,可以使用 https://nodejs.org/api/path.html#path_path_basename_path_ext

path.basename('/foo/bar/baz/asdf/quux.html', '.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); //python

var base = path.parse(filepath).base;
console.log(base); //python.exe

var ext = path.parse(filepath).ext;
console.log(ext); //.exe

path是一个nodeJS模块,这意味着你不需要安装任何包来使用它的属性。

import path from 'path'
const dir_name = path.basename('/Users/Project_naptha/demo_path.js')
console.log(dir_name)

// returns
demo_path.js