esm: add import.meta.dirname and import.meta.filename
This PR adds import.meta.dirname
and import.meta.filename
for ECMAScript Modules that are loaded from the local filesystem. In my view, these properties don’t make any sense for modules loaded from the network, but they are very desired for local modules. At least one recent issue (https://github.com/nodejs/node/issues/47756) wanted them, and there exists at least two ecosystem modules to solve for them:
The Problem
As it stands, to determine the containing directory of a script we must write code like:
import url from 'url'
import path from 'path'
const dirname = path.dirname(url.fileURLToPath(import.meta.url))
Of course, this needs to be repeated in every script that needs the information. With this PR, the code is reduced to:
const dirname = import.meta.__dirname
The developer doesn’t need to remember how to convert the file URL to a path and then resolve the directory from that.
External Discussion
The impetus for this PR is a recent Twitter discussion – https://twitter.com/jasnell/status/1677335322978295809
Notable change
In file:
-based ES modules, new properties import.meta.filename
and import.meta.dirname
provide equivalents to CommonJS __filename
and __dirname
. In particular, import.meta.filename
provides the full absolute path (as a file path, not URL) to the module; and import.meta.dirname
provides the full absolute path to the module’s containing folder. These properties are missing for non-file:
-based ES modules, such as those loaded from data:
or https:
URLs.