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

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;

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