How to Fix __dirname is not defined in ES module scope in Node.js

To fix the __dirname is not defined in ES module scope error in Node.js, you must “create a custom __dirname”. In Node.js, the __dirname global is unavailable in ES modules (i.e., when using import and export syntax instead of require and module.exports).

Example

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

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

Here’s what’s happening in this code:

  1. import.meta.url is a property provided in ES modules in Node.js that contains the URL of the current module.
  2. fileURLToPath is a function from the ‘url’ module that converts a file:// URL to a path string.
  3. dirname is a function from the ‘path’ module that gives you the directory name of a path.

By using these together, you can get the directory name of the current module in an ES module in Node.js. This code effectively recreates __dirname in a way that works in ES modules.

Please note that you need to add this code to every module where you want to use __dirname, as each module has its own separate scope in JavaScript.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.