If you’ve been working with Node.js and switched from CommonJS (require) to ES Modules (import/export), you might have run into a frustrating error:
ReferenceError: __dirname is not defined in ES module scope
This happens because in CommonJS, Node.js automatically provides special variables like __dirname and __filename. These help identify the current file path or directory name. However, when you use ES modules (.mjs files or "type": "module" in package.json), these variables are no longer available by default.
So, how do you fix this? Let’s walk through one of the most reliable solutions.
Why This Error Occurs
In CommonJS, __dirname is built-in. But with ES Modules, Node.js relies on a different system that doesn’t include these globals. Instead, it uses URL-based module resolution
.
That means when you try to use __dirname in an ES module, Node.js throws the error because it simply doesn’t exist in that scope.
Solution: Use import.meta.url with fileURLToPath
The recommended way to recreate __dirname in ES Modules is by combining import.meta.url with Node’s fileURLToPath utility from the url module.
Here’s how you can do it:
// file: example.mjs
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// Recreate __filename and __dirname in ES module scope
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log(__dirname);
console.log(__filename);
How this works:
import.meta.url
gives you the URL of the current ES module file.
fileURLToPath(import.meta.url)
converts that URL into a local file path.
dirname(__filename)
extracts the directory path, replicating the behavior of __dirname
in CommonJS.
This way, your code works almost exactly as it would in a CommonJS module — except now it’s compatible with ES Modules.
When to Use This
You’ll need this approach whenever your code:
Works with file systems (e.g., fs
module for reading/writing files).
Needs relative paths for static assets or configurations.
Runs in ES Module scope (using import/export
instead of require
).
By implementing this fix, you can make sure your Node.js application stays consistent and avoids breaking when moving between CommonJS and ES Modules.
Final Thoughts
The ReferenceError: __dirname is not defined in ES module scope
can be confusing if you’re transitioning to ES Modules for the first time. Fortunately, using import.meta.url
and fileURLToPath
makes it easy to reintroduce familiar functionality.
In this article, I’ve shared one reliable fix for the problem. But there are actually a couple of other ways to solve this depending on your setup. For a complete guide with all three solutions and more code examples, check out my full write-up here:
👉 Fixing ReferenceError: __dirname is Not Defined in ES Module Scope (Full Guide)
Top comments (0)