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

The __dirname is not defined in ES module scope error occurs in JavaScript when you “try to access the __dirname global variable in an ES module.” The __dirname and __filename global variables are defined in CommonJS modules but not in ES modules.

To fix the “__dirname is not defined in the ES module scope” error in Node.js, you must use “specific functions to create a custom __dirname variable that works just like the global variable, containing the full path of the file’s current working directly.”

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 separate scope in JavaScript.

Create utility for __dirname and __filename

If you can access the __dirname and __filename variables frequently, we can abstract the logic for creating them in a utility module and avoid unnecessary repetition.

Example

Create a file called utility.js and add the below code.

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

export default function fileDirName(meta) {
  const __filename = fileURLToPath(meta.url);

  const __dirname = dirname(__filename);

  return { __dirname, __filename };
}

Now, you can use the utility across our project’s various other module files.

import { dirname } from 'path';

export default function fileDirName(meta) {
  const __filename = fileURLToPath(meta.url);

  const __dirname = dirname(__filename);

  return { __dirname, __filename };
}

That’s it.

Leave a Comment

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