Alternative for __dirname in node when using the -

2019-03-17 12:41发布

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?

5条回答
对你真心纯属浪费
2楼-- · 2019-03-17 13:01
import path from 'path';
const __dirname = path.join(path.dirname(decodeURI(new URL(import.meta.url).pathname)));

This code also works on Windows

查看更多
乱世女痞
3楼-- · 2019-03-17 13:03

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;
查看更多
smile是对你的礼貌
4楼-- · 2019-03-17 13:03

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.

查看更多
Deceive 欺骗
5楼-- · 2019-03-17 13:06

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.

查看更多
\"骚年 ilove
6楼-- · 2019-03-17 13:16

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);
查看更多
登录 后发表回答