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

Amygdaloideum picture Amygdaloideum · Oct 14, 2017 · Viewed 22.4k times · Source

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?

Answer

GOTO 0 picture GOTO 0 · Apr 26, 2018

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