• Node.js Video Tutorials

Node.js - path.dirname() 方法



Node.js 的 path.dirname() 方法是 path 模組的一個輔助方法,用於獲取指定路徑的父目錄。當您需要確定應用程式或指令碼正在從哪個資料夾執行,或者想要找出某個檔案在檔案系統中的位置時,此方法非常有用。

而在基於 LINUX 的系統上,我們可以使用 dirname 命令獲取路徑的目錄名稱部分。此方法會忽略尾隨的目錄分隔符。

語法

以下是 path 模組中 Node.js path.dirname() 方法的語法:

path.dirname( path )

引數

  • path - 此引數儲存將用於提取該特定檔案目錄名稱的檔案路徑。如果 path 不是字串,則會丟擲 TypeError。

返回值

此方法返回一個字串,該字串指定指定檔案路徑的目錄名稱。這有助於解析路徑以確定檔案相對於另一個檔案或資料夾的位置。

示例

如果我們將 path 引數傳遞給該方法,它將返回指定 path 的目錄名稱部分。

在以下示例中,我們嘗試使用 os 模組的 Node.js path.dirname() 方法獲取指定檔案 path (Nodefile.js) 的目錄名稱。

const path = require('path');

const path1 = path.dirname("C:/Users/Lenovo/Desktop/JavaScript/Nodefile.js");
console.log("The Directory name of the file path (Nodefile.js) is: " + path1);

輸出

執行上述程式後,path.dirname() 返回給定檔案路徑的目錄名稱部分。

The Directory name of the file path (Nodefile.js) is: C:/Users/Lenovo/Desktop/JavaScript

示例

如果我們將不是 string 型別的值傳遞給 path 引數,則該方法將丟擲 TypeError

在以下示例中,我們將 integer 而不是 string 傳遞給該方法的 path 引數。

const path = require('path');

const path1 = path.dirname(6576543);
console.log("The Directory name of the path (Nodefile.js) is: " + path1);

TypeError

如果我們編譯並執行上述程式,則 path.dirname() 方法會丟擲 TypeError,因為 path 引數不是 string 值。

For Output Code pre classpath.js:39
   throw new ERR_INVALID_ARG_TYPE('path', 'string', path);
   ^

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type number
   at assertPath (path.js:39:11)
   at Object.dirname (path.js:1270:5)
   at Object.<anonymous> (/home/cg/root/63a028ab0650d/main.js:3:20)
   at Module._compile (internal/modules/cjs/loader.js:702:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
   at Module.load (internal/modules/cjs/loader.js:612:32)
   at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
   at Function.Module._load (internal/modules/cjs/loader.js:543:3)
   at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
   at startup (internal/bootstrap/node.js:238:19)

示例

以下是獲取指定檔案路徑的目錄名稱部分的另一種方法。

const path = require('path');

console.log("The file path of (Nodefile.js): " + __filename);
const path1 = path.dirname(__filename);
console.log("The Directory name portion of the file is: " + path1);

輸出

如果我們在線上編譯器中執行程式碼,它將根據 POSIX 作業系統顯示結果。

以下是上述程式的輸出:

The file path of (Nodefile.js): /home/cg/root/63a028ab0650d/main.js
The Directory name portion of the file is: /home/cg/root/63a028ab0650d

當我們在 WINDOWS 作業系統上執行上述程式時,“__filename” 將獲取當前檔案路徑,並且 path.dirname() 方法將返回當前檔案路徑的目錄名稱部分。

The file path of (Nodefile.js): C:\Users\Lenovo\Desktop\JavaScript\nodefile.js
The Directory name portion of the file is: C:\Users\Lenovo\Desktop\JavaScript
nodejs_path_module.htm
廣告