/

How to Fix the \"__dirname is not defined in ES module scope\" Error

How to Fix the “__dirname is not defined in ES module scope” Error

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:

  1. Import the Node.js path module and the fileURLToPath function from the url module:
1
2
import path from 'path';
import { fileURLToPath } from 'url';
  1. Replicate the functionality of __dirname using the following code:
1
2
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.

  1. Finally, you can use __dirname as you normally would:
1
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.

tags: [“JavaScript”, “Node.js”, “ES module”, “__dirname error”, “technical blog”]