Node.js path.dirname() 方法
path.dirname() 方法用于获取给定路径的目录名称。它忽略相应平台的尾随目录分隔符。
句法:
path.dirname( path )
参数:此函数接受一个如上所述和如下所述的参数:
- path:它是用于提取目录名称的文件路径。如果此参数不是字符串值,则会引发 TypeError。
返回值:它返回一个带有路径目录的字符串。
下面的程序说明了 Node.js 中的path.dirname() 方法:
示例 1:
// Node.js program to demonstrate the
// path.dirname() method
// Import the path module
const path = require('path');
// Complete file path
path1 = path.dirname("/users/admin/website/index.html");
console.log(path1)
// Only file name
// returns a period (.)
path2 = path.dirname("readme.md");
console.log(path2)
// Path with file not specified
path3 = path.dirname("website/post/comments")
console.log(path3);
输出:
/users/admin/website
.
website/post
示例 2:
// Node.js program to demonstrate the
// path.dirname() method
// Import the path module
const path = require('path');
console.log("File name:", __filename);
path1 = path.dirname(__filename);
console.log(path1);
console.log("Directory name:", __dirname);
path2 = path.dirname(__dirname);
console.log(path2);
输出:
File name: G:\tutorials\nodejs-path-dirname\index.js
G:\tutorials\nodejs-path-dirname
Directory name: G:\tutorials\nodejs-path-dirname
G:\tutorials
参考: https://nodejs.org/api/path.html#path_path_dirname_path