Node.js 檔案路徑

系統中的每個檔案都有一個路徑。在 Linux 和 macOS 上,路徑可能如下所示:/users/joe/file.txt,而 Windows 計算機則不同,其結構類似於:C:\users\joe\file.txt

在應用程式中使用路徑時需要注意,因為必須考慮到這種差異。

你可以使用 const path = require('node:path'); 將此模組包含在檔案中,然後就可以開始使用它的方法了。

從路徑中獲取資訊

給定一個路徑,你可以使用以下方法從中提取資訊:

  • dirname:獲取檔案的父資料夾
  • basename:獲取檔名部分
  • extname:獲取副檔名

示例

const  = ('node:path');

const  = '/users/joe/notes.txt';

.(); // /users/joe
.(); // notes.txt
.(); // .txt

你可以透過為 basename 指定第二個引數來獲取不帶副檔名的檔名。

path.basename(notes, path.extname(notes)); // notes

處理路徑

你可以使用 path.join() 連線路徑的兩個或多個部分。

const  = 'joe';
path.join('/', 'users', , 'notes.txt'); // '/users/joe/notes.txt'

你可以使用 path.resolve() 獲取相對路徑的絕對路徑計算結果。

path.resolve('joe.txt'); // '/Users/joe/joe.txt' if run from my home folder

在這種情況下,Node.js 會簡單地將 /joe.txt 附加到當前工作目錄。如果你指定了第二個引數資料夾,resolve 將使用第一個作為第二個的基礎。

path.resolve('tmp', 'joe.txt'); // '/Users/joe/tmp/joe.txt' if run from my home folder

如果第一個引數以斜槓開頭,則表示它是一個絕對路徑。

path.resolve('/etc', 'joe.txt'); // '/etc/joe.txt'

path.normalize() 是另一個有用的函式,它會在路徑包含相對說明符(如 ...)或雙斜槓時,嘗試計算實際路徑。

path.normalize('/users/joe/..//test.txt'); // '/users/test.txt'

resolvenormalize 都不會檢查路徑是否存在。它們只是根據獲得的資訊計算路徑。