Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert local file path to a file::?/ url safely in node.js?

Tags:

I have local file paths (in node.js) and I need to convert them into file:// urls.

I'm now looking at https://en.wikipedia.org/wiki/File_URI_scheme and I feel this must be a solved problem and somebody must have a snippet or npm module to do this.

But then I try to search npm for this but I get so much cruft it is not funny (file, url and path are a search hit in like every package ever :) Same with google and SO.

I can do this naïve approach

site = path.resolve(site); if (path.sep === '\\') {     site = site.split(path.sep).join('/'); } if (!/^file:\/\//g.test(site)) {     site = 'file:///' + site; } 

But I'm pretty sure that is not the way to go.

like image 518
Bartvds Avatar asked Dec 16 '13 19:12

Bartvds


People also ask

How do I change a local file to URL?

There is no way to convert it, unless you are going to buy a hosting and domain using your desired domain name.

Can a file path be a URL?

file is a registered URI scheme (for "Host-specific file names"). So yes, file URIs are URLs.

How do I change the path of a link?

If you're using Windows 10, hold down Shift on your keyboard and right-click on the file, folder, or library for which you want a link. If you're using Windows 11, simply right-click on it. Then, select “Copy as path” in the contextual menu.


2 Answers

Node.js v10.12.0 just got two new methods to solve this issue:

const url = require('url'); url.fileURLToPath(url) url.pathToFileURL(path) 

Documentation

  • https://nodejs.org/api/url.html#url_url_pathtofileurl_path
  • https://nodejs.org/api/url.html#url_url_fileurltopath_url
like image 144
HaNdTriX Avatar answered Oct 15 '22 15:10

HaNdTriX


Use the file-url module.

npm install --save file-url 

Usage:

var fileUrl = require('file-url');  fileUrl('unicorn.jpg'); //=> file:///Users/sindresorhus/dev/file-url/unicorn.jpg   fileUrl('/Users/pony/pics/unicorn.jpg'); //=> file:///Users/pony/pics/unicorn.jpg 

Also works in Windows. And the code is simple enough, in case you want to just take a snippet:

var path = require('path');  function fileUrl(str) {     if (typeof str !== 'string') {         throw new Error('Expected a string');     }      var pathName = path.resolve(str).replace(/\\/g, '/');      // Windows drive letter must be prefixed with a slash     if (pathName[0] !== '/') {         pathName = '/' + pathName;     }      return encodeURI('file://' + pathName); }; 
like image 39
Camilo Martin Avatar answered Oct 15 '22 16:10

Camilo Martin