Sometimes, we want to use __dirname in Node.js when using ES6 modules.
In this article, we’ll look at how to use __dirname in Node.js when using ES6 modules.
How to use __dirname in Node.js when using ES6 modules?
To use __dirname in Node.js when using ES6 modules, we can use the path
module’s dirname
function.
For instance, we write
import {
dirname
} from 'path';
import {
fileURLToPath
} from 'url';
const __dirname = dirname(fileURLToPath(
import.meta.url));
to call dirname
with the import.meta.url
to convert to a path in the Node.js project.
import.meta.url
has the URL of the current script.
and we use fileURLToPath
to convert the URL to a path.
Conclusion
To use __dirname in Node.js when using ES6 modules, we can use the path
module’s dirname
function.