• Node.js Video Tutorials

NodeJS - fileURLToPath(url) Method



The NodeJS url.fileURLToPath() method of the class URL accepts a file URL string or URL object and converts them as a properly encoded path. This method will make sure that the percent-encoded characters are decoded absolutely. The URL module of Node.js provides various utilities for URL resolution and parsing.

Syntax

Following is the syntax of the NodeJS url.fileURLToPath() method of class URL

url.fileURLToPath(url)

Parameters

  • url: This parameter specifies a file URL string or URL object that will be converted to a path.

Return Value

This method returns a fully-resolved platform-specific Node.js file path.

Example

If a file URL string is passed to the NodeJS url.fileURLToPath() method, it will convert as a fully-resolved platform-specific path.

In the following example, we are passing a file URL string to the NodeJS url.fileURLToPath() method.

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

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

Output

On executing the above program, it will generate the following output

C:\Desktop\file\

Example

On Windows, if the file URL string includes non-ASCII characters, the fileURLToPath() method fails to convert as a fully-resolved path and it returns a TypeError.s

In the following example, we are passing a file URL string containing Japanese characters to the fileURLToPath() method.

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

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

TypeError

On executing the above program, it will generate the following output

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
Advertisements