URL.pathToFileURL() is a Node.js method used to convert a local path into a properly formatted file: URL. It handles path formatting details automatically so the resulting file URL is valid and consistent across platforms.
- Adjusts path separators and special characters during conversion
- Works with platform-specific path structures such as Windows and POSIX paths
Syntax:
URL.pathToFileURL(path)where,
path:The filesystem path to be converted into afile:URL.
Return Value: This function returns the file URL object.
Example 1:
// Node program to demonstrate the
// URL.pathToFileURL API as Setter
// Importing the module 'url'
const url = require('url');
// Some random path from system
const path = 'D:\GeeksForGeeks'
// Converting the path to properly encoded file
console.log(url.pathToFileURL(path))
In this code, url.pathToFileURL() converts a local file system path into a properly encoded file URL and displays the result.
Output:
URL {
href: 'file:///D:/GeeksForGeeks',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/D:/GeeksForGeeks',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
Example 2:
// Node program to demonstrate the
// URL.pathToFileURL API as Setter
// Importing the module 'url'
const url = require('url');
// Some random path from system
const path = 'D:\NodeJS\node_modules\npm'
// Converting the path to properly encoded file
console.log(url.pathToFileURL(path))
In this code, url.pathToFileURL() converts the specified local directory path into a properly encoded file: URL and prints it.
Output:
URL {
href: 'file:///D:/NodeJS%0Aode_modules%0Apm',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/D:/NodeJS%0Aode_modules%0Apm',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
Use Cases of URL.pathToFileURL() API
- Convert file paths to file URLs: Transforms local file system paths into valid
file:URLs. - ES Module imports: Creates file URLs for dynamic module loading.
- URL-based APIs: Provides file URLs for APIs that accept URLs instead of file paths.
Reference: https://nodejs.org/api/url.html#url_url_pathtofileurl_path