Kinda Code
Home/Node/Node.js: Using __dirname and __filename with ES Modules

Node.js: Using __dirname and __filename with ES Modules

Last updated: February 12, 2023

If you’re building a Node.js application with ES modules instead of CommonJS modules (“import” instead of “require”, in simpler terms), you have to do something before writing __filename and __direname in your code.

The Problem

In Node.js:

  • __filename: Returns the absolute path to the current file
  • __dirname: Returns the absolute path to the parrent folder

Those things are not ready to be used if you’re working with ES modules and you will encounter the following errors:

ReferenceError: __dirname is not defined in ES module scope

And:

ReferenceError: __filename is not defined in ES module scope

Don’t panic. The solution is only a few lines of code.

The Solution

Here’s how we solve the problem:

import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

console.log(__filename);
console.log(__dirname);

When executing the preceding code, you will see an output similar to this (your paths won’t be exactly the same as mine, of course):

/Users/goodman/Desktop/Dev/node/node_kindacode/src/index.js
/Users/goodman/Desktop/Dev/node/node_kindacode/src

Conclusion

You’ve learned how to use __dirname and __filename when working with ES6 modules in Node.js. If you’d like to explore more modern and exciting stuff about the Javascript runtime, take a look at the following articles:

You can also check out our Node.js category page for the latest tutorials and examples.