The Node.js URL.fileURLToPath() API converts a file: URL into a filesystem path string. It is useful when working with file locations represented as URLs and needing them in a format suitable for filesystem operations.
Syntax:
url.fileURLToPath(url)where,
url: Afile:URL as a string or aURLobject.
Return Value: The corresponding filesystem path as a string.
Example 1:
// Node program to demonstrate the
// URL.fileURLToPath() API
// Importing the module 'url'
const url = require('url');
// Some random path from system
const file = 'file://computerscience/geeksforgeeks.txt'
// Converting our file to properly encoded path
console.log(url.fileURLToPath(file))
In this code, url.fileURLToPath() converts a UNC-style file: URL into a Windows network path.
Output:
\\computerscience\geeksforgeeks.txtExample 2:
// Node program to demonstrate the
// URL.fileURLToPath() API
// Importing the module 'url'
const url = require('url');
// Some random path from system
const file = 'file:///C:/path/example/gfg'
// Converting the file to properly encoded path
console.log(url.fileURLToPath(file))
In this code, url.fileURLToPath() converts a file: URL with a drive letter into a standard Windows absolute path.
Output:
C:\path\example\gfg Use cases of URL.fileURLToPath() API
- Convert file URLs to paths: Transforms
file:URLs into local filesystem paths for use with Node.jsfsAPIs. - ES Module path handling: Obtains file paths from
import.meta.urlin ES modules. - Decode URL-encoded characters: Resolves percent-encoded characters like
%20back to their original form (e.g., spaces) in file paths.
Reference: https://nodejs.org/api/url.html#url_url_fileurltopath_url