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

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("https://stackoverflow.com/");
}
if (!/^file:\/\//g.test(site)) {
    site="file:///" + site;
}

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

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

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, "https://stackoverflow.com/");

    // Windows drive letter must be prefixed with a slash
    if (pathName[0] !== "https://stackoverflow.com/") {
        pathName="https://stackoverflow.com/" + pathName;
    }

    return encodeURI('file://' + pathName);
};

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'


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How do I preserve line breaks when getting text from a textarea?

Similar Posts