紀錄工作經驗、相關知識,解決技術相關問題。

Node JS

Node.js path.join() 用法:路徑串接、Windows 與 Linux 分隔符差異

Node.js path.join() 用法:路徑串接、Windows 與 Linux 分隔符差異 特色圖片

path.join() 會把多段路徑用目前作業系統的分隔符(Windows 是 \,Linux/macOS 是 /)串起來,再整理掉多餘的 /、. 與 ..。

import path from 'node:path';

const file = path.join('src', 'images', 'logo.png');
console.log(file);
// Linux / macOS:src/images/logo.png
// Windows:     src\images\logo.png

語法

path.join([...paths])
  • ...paths:任意數量的字串路徑片段。
  • 回傳值:串接並整理後的路徑字串。
  • path.join() 從 Node.js v0.1.16 就有,所有仍在維護的 Node.js 版本都能用。CommonJS 寫法是 const path = require('node:path');。

範例

1. 串接資料夾與檔名

import path from 'node:path';

console.log(path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'));
// Linux / macOS:/foo/bar/baz/asdf
// Windows:     \foo\bar\baz\asdf

最後的 .. 代表回到上一層,所以 quux 被抵銷。

2. 以目前檔案所在資料夾為基準

ES Module 沒有 __dirname,Node.js 20.11 起可以用 import.meta.dirname(Node.js 22.16、24.0 起不再標為實驗性功能):

import path from 'node:path';

const configPath = path.join(import.meta.dirname, 'config', 'app.json');

CommonJS 則直接用 __dirname:

const path = require('node:path');

const configPath = path.join(__dirname, 'config', 'app.json');

3. 固定輸出 / 或 \

產生網址路徑、或要在 Windows 上組出 Linux 伺服器的路徑時,用 path.posix.join();反過來用 path.win32.join():

import path from 'node:path';

console.log(path.posix.join('src', 'images', 'logo.png')); // src/images/logo.png
console.log(path.win32.join('src', 'images', 'logo.png')); // src\images\logo.png

注意事項

path.join() 和 path.resolve() 的差別

path.join() 只是照順序串起來;path.resolve() 遇到以 / 開頭的片段會從那裡重新開始,而且一定回傳絕對路徑。

import path from 'node:path';

console.log(path.posix.join('/var/www', '/uploads', 'a.png'));    // /var/www/uploads/a.png
console.log(path.posix.resolve('/var/www', '/uploads', 'a.png')); // /uploads/a.png

空字串與全部為空

空字串片段會被忽略;全部都是空字串時回傳 '.'(代表目前工作目錄)。

console.log(path.posix.join('a', '', 'b')); // a/b
console.log(path.join('', ''));             // .

結尾的 / 會保留

console.log(path.posix.join('docs/', '/guide/')); // docs/guide/

.. 可以跳出起點

path.join() 不會阻止路徑往上跳。把使用者輸入的檔名直接拿來串接,可能被 ../ 帶到預期外的資料夾,處理上傳或下載路徑時要另外檢查結果是否仍在允許的資料夾內。

console.log(path.posix.join('uploads', '../../etc/passwd')); // ../etc/passwd

參數必須是字串

傳入物件、undefined 等非字串值會丟出 TypeError(錯誤代碼 ERR_INVALID_ARG_TYPE)。

path.join('foo', {}, 'bar'); // TypeError [ERR_INVALID_ARG_TYPE]

參考資料與延伸閱讀

發佈留言