Node: Create a file URI from a file path on Windows

Created on 16 Apr 2018  ·  2Comments  ·  Source: nodejs/node

  • Version: v8.7.0
  • Platform: Windows 10 64bit
  • Subsystem:


In Windows, one may have a file path
const filePath = 'C:\Users\myname\test.swf'
and may want to create a standard file URI from it. To do so, one can use the url.format method

const fileUrl = url.format({ protocol: 'file', slashes: true, pathname: filePath, });
but this doesn't create a URL that follows the standard for file URI (RFC 8089). Instead it creates something like file:///C:\Users\myname\test.swf, where, according to the standard, the \ should be /, which would be file:///C:/Users/myname/test.swf.

A workaround I have found is to wrap it in a parse and get the href
const fileUrl = url.parse(url.format({ protocol: 'file', slashes: true, pathname: filePath, })).href;
or do something similar just with the filePath.

There is a simple third-party node module (file-url) that does this exact conversion for you, but I think it should be a standard output of url.format or at least an option.

If there is something already doing this, I haven't found it and would be happy for any feedback.

Thanks!

question url whatwg-url

Most helpful comment

use the new WHATWG URL implementation:

const path = 'c:\\Users\\myname\\test.swf';
const u = new URL(`file:///${path}`);
// u.href = 'file:///c:/Users/myname/test.swf'

All 2 comments

use the new WHATWG URL implementation:

const path = 'c:\\Users\\myname\\test.swf';
const u = new URL(`file:///${path}`);
// u.href = 'file:///c:/Users/myname/test.swf'

🤦‍♂️ Yup, that is exactly what I wanted and it works on both Mac and Windows. Thank you!

Was this page helpful?
0 / 5 - 0 ratings