当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js path.resolve()用法及代码示例


path.resolve()方法用于将path-segments序列解析为绝对路径。它通过处理从右到左的路径顺序来工作,在每个路径之前添加,直到创建绝对路径为止。生成的路径被规范化并根据需要删除了斜杠。如果没有路径段作为参数给出,则使用当前工作目录的绝对路径。

path.resolve( [...paths] )

参数:该函数接受上面提到并在下面描述的一个参数:

  • 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)

输出:

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:

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\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



相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Node.js | path.resolve() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。