Dec 14, 2023
1 min read
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:
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:
|
|
Now, __dirname
will be defined within the module.
If you’re working in a module and need to use __dirname
across multiple files, consider creating a utility module:
|
|
Then, in your main module, import and use it:
|
|
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!