Node | URL.pathToFileURL API

This URL.pathToFileURL function converts the path to a file and ensures that the URL control characters (/, \, : ) are correctly appended/adjusted when converting the given path into a File URL.

Syntax:

url.pathToFileURL(path)

Parameters: This function accepts single parameter path which holds the path to convert a file URL.



Return Value: This function returns the file URL object.

Below programs illustrates the use of URL.-pathToFileURL Method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node program to demonstrate the  
// URL.pathToFileURL API as Setter
   
// Importing the module 'url' 
var url = require('url');
  
// Some random path from system
const path = 'D:\GeeksForGeeks'
  
// Converting the path to properly encoded file
console.log(url.pathToFileURL(path)) 

chevron_right


Output:

 
URL {
  href: 'file:///D:/GeeksForGeeks',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/D:/GeeksForGeeks',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node program to demonstrate the  
// URL.pathToFileURL API as Setter
   
// Importing the module 'url' 
var 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)) 

chevron_right


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: ''
}

Note: The above program will compile and run by using the node app.js command.

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.