Skip to content

How to fix "__dirname is not defined in ES module scope"

New Course Coming Soon:

Get Really Good at Git

Here is how to fix the "__dirname is not defined in ES module scope" error

I stumbled on this error while I used __dirname inside a 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 this, 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 filename of the code which is executed.

Now you can use __dirname as usual:

console.log(__dirname)
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Node.js Handbook
→ Read my Node.js Tutorial on The Valley of Code

Here is how can I help you: