Node.js path.resolve() 方法
path.resolve() 方法用于将一系列路径段解析为绝对路径。它通过处理从右到左的路径序列来工作,在每个路径之前添加,直到创建绝对路径。生成的路径被规范化,并根据需要删除尾部斜杠。
如果没有给出路径段作为参数,则使用当前工作目录的绝对路径。
句法:
path.resolve( [...paths] )
参数:此函数接受一个如上所述和如下所述的参数:
- 路径:它是一系列文件路径,它们将一起解析形成绝对路径。如果此参数不是字符串值,则会引发 TypeError。
返回值:返回一个带有绝对路径的字符串。
下面的程序说明了 Node.js 中的path.resolve() 方法:
示例 1:
Node.js
// Node.js program to demonstrate the
// path.resolve() Method
// Import the path module
const path = require('path');
console.log("Current directory:", __dirname);
// Resolving 2 path-segments
// with the current directory
path1 = path.resolve("users/admin", "readme.md");
console.log(path1)
// Resolving 3 path-segments
// with the current directory
path2 = path.resolve("users", "admin", "readme.md");
console.log(path2)
// Treating of the first segment
// as root, ignoring the current directory
path3 = path.resolve("/users/admin", "readme.md");
console.log(path3)
Node.js
// Node.js program to demonstrate the
// path.resolve() Method
// Import the path module
const path = require('path');
console.log("Current directory:", __dirname);
// Normalization of the absolute paths
path1 = path.resolve("users", "..", "readme.md");
console.log(path1)
path2 = path.resolve("users", "admin",
"..", "files", "readme.md");
console.log(path2)
path3 = path.resolve("users", "admin",
"..", "files", "..", "readme.md");
console.log(path3)
输出:
Current directory: G:\tutorials\nodejs-path-resolve
G:\tutorials\nodejs-path-resolve\users\admin\readme.md
G:\tutorials\nodejs-path-resolve\users\admin\readme.md
G:\users\admin\readme.md
示例 2:
节点.js
// Node.js program to demonstrate the
// path.resolve() Method
// Import the path module
const path = require('path');
console.log("Current directory:", __dirname);
// Normalization of the absolute paths
path1 = path.resolve("users", "..", "readme.md");
console.log(path1)
path2 = path.resolve("users", "admin",
"..", "files", "readme.md");
console.log(path2)
path3 = path.resolve("users", "admin",
"..", "files", "..", "readme.md");
console.log(path3)
输出:
Current directory: G:\tutorials\nodejs-path-resolve
G:\tutorials\nodejs-path-resolve\readme.md
G:\tutorials\nodejs-path-resolve\users\files\readme.md
G:\tutorials\nodejs-path-resolve\users\readme.md
参考: https://nodejs.org/api/path.html#path_path_resolve_paths