Alternative for __dirname in node when using the -

2019-03-17 13:00发布

问题:

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?

回答1:

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);


回答2:

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;


回答3:

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.



回答4:

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.



回答5:

import path from 'path';
const __dirname = path.join(path.dirname(decodeURI(new URL(import.meta.url).pathname)));

This code also works on Windows