Node.js URL.fileURLToPath API

Last Updated : 4 Aug, 2026

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: A file: URL as a string or a URL object.

Return Value: The corresponding filesystem path as a string.

Example 1:

javascript
// 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.txt

Example 2:

javascript
// 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.js fs APIs.
  • ES Module path handling: Obtains file paths from import.meta.url in ES modules.
  • Decode URL-encoded characters: Resolves percent-encoded characters like %20 back to their original form (e.g., spaces) in file paths.

Reference: https://nodejs.org/api/url.html#url_url_fileurltopath_url

Comment

Explore