How to Fix Error Dirname Is Not Defined in Es Module Scope in NodeJS

Dec 14, 2023

1 min read

Published in

Resolving “__dirname is not defined” Error in Node.js ES Modules

When working with ES Modules in Node.js, you might encounter the error “ReferenceError: __dirname is not defined.”

This is because ES Modules handle module scope differently compared to CommonJS. To resolve this issue, follow these steps:

1. Use import.meta.url

Instead of relying on __dirname, use import.meta.url to get the current module’s URL. You can then use the new URL() constructor to extract the directory path:

1
2
3
4
5
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

Now, __dirname will be defined within the module.

2. Implementing in a Module

If you’re working in a module and need to use __dirname across multiple files, consider creating a utility module:

1
2
3
4
5
6
// util.js
import { fileURLToPath, pathToFileURL } from 'url';
import { dirname } from 'path';

export const __filename = fileURLToPath(import.meta.url);
export const __dirname = dirname(__filename);

Then, in your main module, import and use it:

1
2
3
4
// main.js
import { __dirname } from './util.js';

console.log(__dirname);

This approach keeps your code modular and easy to maintain. With these adjustments, you can effectively resolve the “__dirname is not defined” error in Node.js ES Modules. Happy coding !

Sharing is caring!