Node.js | path.join() 方法
path.join() 方法用于使用特定于平台的分隔符连接多个路径段以形成单个路径。在连接发生后,最终路径被规范化。路径段使用逗号分隔值指定。
句法:
path.join( [...paths] )
参数:此函数接受一个如上所述和如下所述的参数:
- 路径:这是一个逗号分隔的路径序列,这些路径将连接在一起形成最终路径。
返回值:它返回一个包含所有段的完整规范化路径的字符串。
下面的示例说明了 Node.js 中的path.join() 方法:
示例 1:
Node.js
// Node.js program to demonstrate the
// path.join() Method
// Import the path module
const path = require('path');
// Joining 2 path-segments
path1 = path.join("users/admin/files", "index.html");
console.log(path1)
// Joining 3 path-segments
path2 = path.join("users", "geeks/website", "index.html");
console.log(path2)
// Joining with zero-length paths
path3 = path.join("users", "", "", "index.html");
console.log(path3)
Node.js
// Node.js program to demonstrate the
// path.join() Method
// Import the path module
const path = require('path');
// Normalizing of the final path
path1 = path.join("users", "..", "files", "readme.md");
console.log(path1)
// Zero length final path
// returns a period (.)
path2 = path.join("users", "..");
console.log(path2)
// Getting the directory path one folder above
console.log("Current Directory: ", __dirname);
path3 = path.join(__dirname, "..");
console.log("Directory above:", path3)
输出:
users\admin\files\index.html
users\geeks\website\index.html
users\index.html
示例 2:
节点.js
// Node.js program to demonstrate the
// path.join() Method
// Import the path module
const path = require('path');
// Normalizing of the final path
path1 = path.join("users", "..", "files", "readme.md");
console.log(path1)
// Zero length final path
// returns a period (.)
path2 = path.join("users", "..");
console.log(path2)
// Getting the directory path one folder above
console.log("Current Directory: ", __dirname);
path3 = path.join(__dirname, "..");
console.log("Directory above:", path3)
输出:
files\readme.md
.
Dirname: G:\tutorials\nodejs-path-join
Directory above: G:\tutorials
参考: https://nodejs.org/api/path.html#path_path_join_paths