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?
In Node.js 10 there's an alternative that doesn't require creating multiple files:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
There have been proposals about exposing these variables through import.meta
, but for now, you need a hacky workaround that I found here:
// expose.js
module.exports = {__dirname};
// use.mjs
import expose from './expose.js';
const {__dirname} = expose;
I used:
import path from 'path';
const __dirname = path.resolve(path.dirname(decodeURI(new URL(import.meta.url).pathname)));
decodeURI
was important: used spaces and other stuff within the path on my test system.
path.resolve()
handles relative urls.
I also got into this issue, my solution:
./src/app.mjs:
app.set('views', path.join(path.resolve('./src'), 'views'));
Here is information about my folder organization:
./index.mjs
import server from './src/bin/www.mjs';
server.start();
./package.json
"scripts": {
"start": "node --experimental-modules ./index.mjs"
},
It's returning the correct paths on my windows pc as __dirname
.
import path from 'path';
const __dirname = path.join(path.dirname(decodeURI(new URL(import.meta.url).pathname)));
This code also works on Windows