How to get __dirname in es6 module?

Starting with Node.js 20.11 / 21.2, you can use import.meta.dirname:

const __dirname = import.meta.dirname;

From Node.js 10.12 and higher, here's how you can get the directory name:

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

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

This code first imports the fileURLToPath function from the url module and the dirname function from the path module. Then it uses fileURLToPath to convert the URL of the current module (import.meta.url) to a file path, and dirname to get the directory of that file path.