I use the flag --experimental-modules
when running my node application in order to use ES6 modules.
However when I use this flag the metavariable __dirname
is not available. Is there an alternative way to get the same string that is stored in __dirname
that is compatible with this mode?
This code also works on Windows
There have been proposals about exposing these variables through
import.meta
, but for now, you need a hacky workaround that I found here:I also got into this issue, my solution:
./src/app.mjs:
Here is information about my folder organization:
./index.mjs
./package.json
It's returning the correct paths on my windows pc as
__dirname
.I used:
decodeURI
was important: used spaces and other stuff within the path on my test system.path.resolve()
handles relative urls.In Node.js 10 there's an alternative that doesn't require creating multiple files: