26

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.

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Bartvds
  • 3,340
  • 5
  • 30
  • 42
  • 1
    See this post for possible solution: http://stackoverflow.com/questions/18341808/node-js-how-to-handle-a-mix-of-os-and-url-style-paths-correctly/18343553#18343553 – Brian Dec 18 '13 at 18:10

4 Answers4

58

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

HaNdTriX
  • 28,732
  • 11
  • 78
  • 85
25

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);
};
Camilo Martin
  • 37,236
  • 20
  • 111
  • 154
  • 1
    As of file-url version 4.0.0, the developer requires ESM, Node.js 12.0.0+ and no longer supports CommonJS (an error is thrown if you try to use require). Version 3.0.0 still works but 4.0.0 imposes these constraints that may not be acceptable to many developers. I am going to check out the url module and pathToFileURL() method. – Robert G. Schaffrath Apr 19 '21 at 11:21
5

I had a similar issue, but the solution ended up being to use the new WHATWG URL implementation:

const path = 'c:\\Users\\myname\\test.swf';
const u = new URL(`file:///${path}`).href;
// u = 'file:///c:/Users/myname/test.swf'
msanford
  • 11,803
  • 11
  • 66
  • 93
0

Explanation: Here is the solution to converting a path into a file. By using the below method, you have to load the path in fetch, and then the file will load as a blob. Then create a file object using blob.

fetch(src)
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], 'fileName', { type: "image/png" })
    
  })
adnan javed
  • 1,338
  • 8
  • 10