Nodejs module __dirname not found solution

Why

__dirname is not defined in ES module scope, thats why error shows up

Solution

You first need to import the Node.js path module and the fileURLToPath function from the url module:

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

Then you can replicate the functionality of __dirname in this way:

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

const __dirname = path.dirname(__filename);

This, incidentally, also replicates __filename, which returns the filename of the code which is executed.

Now you can use __dirname as usual: