Alternative for __dirname in Node.js when using ES6 modules

Solution 1:

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

Solution 2:

The most standardized way in 2021

import { URL } from 'url'; // in Browser, the URL in native accessible on window

const __filename = new URL('', import.meta.url).pathname;
// Will contain trailing slash
const __dirname = new URL('.', import.meta.url).pathname;

And forget about join to create paths from the current file, just use the URL

const pathToAdjacentFooFile = new URL('./foo.txt', import.meta.url).pathname;
const pathToUpperBarFile = new URL('../bar.json', import.meta.url).pathname;