• Node.js Video Tutorials

NodeJS - url.pathToFileURL() Method



The NodeJS url.pathToFileURL() method of the class URL accepts a path of a file and converts them into a fully-resolved file URL Object.

This method will make sure that the file path is resolved absolutely. If the file path contains URL control characters, they will be encoded and converted into a fully-resolved File URL.

Syntax

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

url.pathToFileURL(path)

Parameters

  • path: This parameter specifies a path that will be converted to a File URL.

Return value

This method returns the file URL object.

Example

If we pass a file path to the NodeJS url.pathToFileURL() method, it will convert that path into a file URL object.

In the following example, we are passing the ‘__filename’ (i.e. it gets the path of the current working file) to the pathToFileURL() method.

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

let PtoF = pathToFileURL(__filename);
console.log(PtoF);

Output

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

URL {
  href: 'file:///C:/Users/Lenovo/Desktop/JavaScript/nodefile.js',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/C:/Users/Lenovo/Desktop/JavaScript/nodefile.js',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}

Example

If the path we pass to the pathToFileURL() method contains URL control characters, it will encode and convert them into a fully-resolved file URL object.

In the following example, we are passing a path to the pathToFileURL() method that contains URL control characters.

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

let PtoF = pathToFileURL('/footer#/file%.js');
console.log(PtoF);

Output

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

URL {
  href: 'file:///C:/footer%23/file%25.js',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/C:/footer%23/file%25.js',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}
nodejs_url_module.htm
Advertisements