How to convert local file path to a file::?/ url safely in node.js?
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);
};
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