AI Workshop: learn to build apps with AI →
ES Modules: How to fix "__dirname is not defined in ES module scope"

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


I stumbled on this error while I used __dirname inside an ES module.

In an ES module, you cannot use __dirname.

Using __dirname in a Node script, you can get the path of the folder where the current JavaScript file resides, and many Node.js projects use this.

But if you use it inside an ES module, you can’t use it, as the infamous “__dirname is not defined in ES module scope” error shows up.

What can you do in this case?

I solved this problem by using a solution I found on the Node.js GitHub issues.

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 path of the file that is being executed.

Now you can use __dirname as usual:

console.log(__dirname)

Lessons in this unit:

0: Introduction
1: How to fix "cannot use import statement outside a module"
2: ▶︎ How to fix "__dirname is not defined in ES module scope"
3: How to fix the error "unexpected token "{". import call expects exactly one argument"
4: How to enable ES Modules in Node.js
5: How to use .env files in Node.js with import syntax
6: How to use import in Node.js
7: Expose functionality from a Node file using exports