Skip to content

new URL('.', import.meta.url).pathname produces erroneous path on Windows 10 #37845

@aral

Description

@aral
  • Version: v14.16.0
  • Platform: Microsoft Windows NT 10.0.19041.0 x64
  • Subsystem: module.import

What steps will reproduce the bug?

const __dirname = new URL('.', import.meta.url).pathname
console.log(__dirname)

How often does it reproduce? Is there a required condition?

Always.

What is the expected behavior?

On Linux and macOS, the snippet of code, above, produces the desired outcome, which is to emulate the __dirname value that exists in CommonJS in a module in an ECMAScript Modules (ESM) project.

If, for example, the above snippet of code is run from index.js in /home/aral/sandbox/dirname-test, the path that is created is the following (and correct):

/home/aral/sandbox/dirname-test/

It should, similarly, create a correct path on Windows.

What do you see instead?

The path that is created in Windows is incorrect.

If, for example, the above snippet of code is run from index.js in C:\Users\aral\sandbox\dirname-test, the path that is created is the following (and is wrong):

/C:/Users/aral/sandbox/dirname-test/

The correct output should be:

C:\Users\aral\sandbox\dirname-test\

Additional information

This updated workaround, based on @devsnek’s reponse, should behave properly across platforms:

import { fileURLToPath } from 'url'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
console.log(__dirname)

(However, the original snippet should also behave correctly on all platforms and doesn’t.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    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