• Node.js Video Tutorials

NodeJS - fileURLToPath(url) 方法



URL 類中的NodeJS url.fileURLToPath() 方法接受檔案 URL 字串或 URL 物件,並將其轉換為正確編碼的路徑。此方法將確保百分比編碼的字元被完全解碼。Node.js 的URL 模組提供了各種用於 URL 解析和分析的實用程式。

語法

以下是URL 類中 NodeJS url.fileURLToPath() 方法的語法

url.fileURLToPath(url)

引數

  • url: 此引數指定將轉換為路徑的檔案 URL 字串或 URL 物件。

返回值

此方法返回一個完全解析的、特定於平臺的 Node.js 檔案路徑。

示例

如果將檔案 URL 字串傳遞給 NodeJS url.fileURLToPath() 方法,它將轉換為完全解析的、特定於平臺的路徑。

在下面的示例中,我們將檔案 URL 字串傳遞給 NodeJS url.fileURLToPath() 方法。

const { fileURLToPath } = require('node:url');

let FtoP = fileURLToPath('file:///C:/Desktop/file/');
console.log(FtoP);

輸出

執行上述程式後,將生成以下輸出

C:\Desktop\file\

示例

在 Windows 系統上,如果檔案 URL 字串包含非 ASCII 字元,則 fileURLToPath() 方法無法將其轉換為完全解析的路徑,並返回 TypeError。

在下面的示例中,我們將包含日語字元的檔案 URL 字串傳遞給 fileURLToPath() 方法。

const { fileURLToPath } = require('node:url');

let FtoP = fileURLToPath('file:///こんにちは:/');
console.log(FtoP);

TypeError

執行上述程式後,將生成以下輸出

node:internal/url:1407
    throw new ERR_INVALID_FILE_URL_PATH('must be absolute');
    ^

TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
    at new NodeError (node:internal/errors:387:5)
    at getPathFromURLWin32 (node:internal/url:1407:11)
    at fileURLToPath (node:internal/url:1437:22)
    at Object.<anonymous> (C:\Users\Lenovo\Desktop\JavaScript\nodefile.js:3:12)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'ERR_INVALID_FILE_URL_PATH'
}
nodejs_url_module.htm
廣告