Node.js fs.realpath() 方法
fs.realPath() 方法用于计算给定路径的规范路径名。它通过解决.
, ..
和路径中的符号链接。
句法:
fs.realpath( path, options, callback )
参数:此方法接受三个参数,如上所述,如下所述:
- path:它保存必须解析的目录的路径。它可以是字符串、缓冲区或 URL。
- options:它是一个字符串或对象,可用于指定将影响操作的可选参数。它有一个可选参数:
- encoding:它是一个字符串,它定义了解析路径的编码。
- callback:方法执行时调用的函数。
- err:如果操作失败将抛出的错误。
- 解析路径:是字符串或缓冲区,表示解析路径。
下面的示例说明了 Node.js 中的fs.realPath() 方法:
示例 1:此示例使用 fs.realPath() 方法获取给定路径的规范路径。
// Node.js program to demonstrate the
// fs.realPath() method
// Import the filesystem module
const fs = require('fs');
console.log("Current Directory Path:", __dirname);
// Finding the canonical path
// one directory up
path1 = __dirname + "\\..";
fs.realpath(path1, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("One directory up resolved"
+ " path is: ", resolvedPath);
}
});
// Finding the canonical path
// two directories up
path2 = __dirname + "\\..\\..";
fs.realpath(path2, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("Two directories up resolved"
+ " path is:", resolvedPath);
}
});
输出:
Current Directory Path: G:\tutorials\nodejs-fs-realPath
Two directories up resolved path is: G:\
One directory up resolved path is: G:\tutorials
示例 2:本示例使用 fs.realPath() 方法来演示不同的编码类型。
// Node.js program to demonstrate the
// fs.realPath() method
// Import the filesystem module
const fs = require('fs');
path = __dirname + "\\..";
// Getting the canonical path in utf8 encoding
fs.realpath(path, {encoding: "utf8"}, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("The resolved path is:", resolvedPath);
}
});
// Getting the canonical path in hex encoding
fs.realpath(path, {encoding: "hex"}, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("The resolved path is:", resolvedPath);
}
});
// Getting the canonical path in base64 encoding
fs.realpath(path, {encoding: "base64"}, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("The resolved path is:", resolvedPath);
}
});
输出:
The resolved path is: G:\tutorials
The resolved path is: 473a5c7475746f7269616c73
The resolved path is: RzpcdHV0b3JpYWxz
参考: https://nodejs.org/api/fs.html#fs_fs_realpath_path_options_callback