If you encounter the “__dirname is not defined in ES module scope” error while using __dirname
in an ES module, here’s how you can fix it.
In a Node script, __dirname
is used to retrieve the path of the folder where the current JavaScript file resides. However, it cannot be used within an ES module, leading to the aforementioned error.
To overcome this issue, follow these steps:
- Import the Node.js
path
module and thefileURLToPath
function from theurl
module:
import path from 'path';
import { fileURLToPath } from 'url';
- Replicate the functionality of
__dirname
using the following code:
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
This code snippet also replicates __filename
, which returns the filename of the executed code.
- Finally, you can use
__dirname
as you normally would:
console.log(__dirname);
By following these steps, you can resolve the “__dirname is not defined in ES module scope” error and continue using __dirname
within your ES module.