__dirname, __filename, path.resolve, path.join, process.cwd

Raymond發表於2023-03-15

MasOs系統,在終端中, /Users/a1234/Desktop/ 目錄下,執行命令 node script/demo.js


\# __dirname - 返回當前模組的目錄名

console.log(__dirname); 
>>> /Users/a1234/Desktop/script

輸出結果: 當前檔案所在目錄的絕對路徑

\# __filename - 返回當前模組檔案的檔名,包含絕對路徑

console.log(__filename); 
>>> /Users/a1234/Desktop/script/demo.js

輸出結果: 當前檔案的絕對路徑

\# path.resolve() - 解析路徑,返回絕對路徑

console.log(path.resolve()); 
>>> /Users/a1234/Desktop

console.log(path.resolve('./demo.js')); 
>>> /Users/a1234/Desktop/demo.js

console.log(path.resolve(__dirname, './demo.js')); 
>>> /Users/a1234/Desktop/script/demo.js

輸出結果: Node.js 程式當前工作的目錄 + 傳入引數(相對路徑)的組合

\# path.join() - 拼接路徑,返回拼接後的路徑

console.log(path.join()); 
>>> .

console.log(path.join('./demo.js')); 
>>> demo.js

console.log(path.join(__dirname, './demo.js')); 
>>> /Users/a1234/Desktop/script/demo.js

輸出結果: 傳入引數(相對路徑)的組合

\# process.cwd() - 返回 Node.js 程式當前工作的目錄

console.log(process.cwd()); 
>>> /Users/a1234/Desktop

輸出結果: Node.js 程式當前工作的目錄


! 總結

優先使用 path.resolve;可以適配絕大多數場景;

相關文章