Alternative for __dirname in node when using the --experimental-modules flag

女生的网名这么多〃 提交于 2019-11-28 07:14:09

As of Node.js 10.12 there's an alternative that doesn't require creating multiple files and handles special characters in filenames across platforms:

import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

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.

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

This code also works on Windows

For Node 10.12 +...

Assuming you are working from a module, this solution should work, and also gives you __filename support as well

import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

The nice thing is that you are also only two lines of code away from supporting require() for CommonJS modules. For that you would add:

import { createRequireFromPath } from 'module';
const require = createRequireFromPath(__filename); 

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.

I made this module es-dirname that will return the current script dirname.

import dirname from 'es-dirname'

console.log(dirname())

It works both in CommonJs scripts and in ES Modules both on Windows and Linux.

Open an issue there if have an error as the script has been working so far in my projects but it might fail in some other cases. For this reason do not use it in a production environment. And this is a temporary solution as I am sure the Node.js team will release a robust way to do it in a near future.

I use this option, since the path starts with file:// just remove that part.

const __filename = import.meta.url.slice(7);
const __dirname = import.meta.url.slice(7, import.meta.url.lastIndexOf("/"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!