Skip to content

Create a file URI from a file path on Windows #20080

Closed

Description

@alexanderturinske
  • 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!

Activity

  1. jasnell commented on Apr 16, 2018

    @jasnell
    Member

    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'
  2. added
    questionIssues asking questions about Node.js.
    urlIssues and PRs related to the legacy built-in url module.
    whatwg-urlIssues and PRs related to the WHATWG URL implementation.
    on Apr 16, 2018
  3. alexanderturinske commented on Apr 16, 2018

    @alexanderturinske
    Author

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

  4. added a commit that references this issue on Jul 2, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionIssues asking questions about Node.js.urlIssues and PRs related to the legacy built-in url module.whatwg-urlIssues and PRs related to the WHATWG URL implementation.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions