當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。