Solve - __dirname is not defined in ES module scope in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Roi Dimor

Solve - __dirname is not defined in ES module scope #

The "__dirname is not defined in ES module scope" error occurs when we try to try to use the __dirname global variable in an ES module file. The __dirname or __filename global variables are not available in ECMAScript module files.

dirname is not defined in es module scope

To solve the "__dirname is not defined in ES module scope" error, import and use the dirname() method from the path module. The dirname method takes a path as a parameter and returns the directory name of the path.

index.js
import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); // 👇️ "/home/john/Desktop/javascript" const __dirname = path.dirname(__filename); console.log('directory-name 👉️', __dirname); // 👇️ "/home/borislav/Desktop/javascript/dist/index.html" console.log(path.join(__dirname, '/dist', 'index.html'));

To get the filename, we had to use the fileURLToPath method from the url module.

The fileURLToPath method returns the fully-resolved platform-specific Node.js file path.

The only parameter the method takes is the file URL string, which should be converted to a path.

The import.meta object contains context-specific metadata for the module - e.g. the module's URL.

index.js
// 👇️ file:///home/john/Desktop/javascript/index.js console.log(import.meta.url);

To get the directory name, we used the dirname method from the path module.

Here's the output from logging the __filename and __dirname variables from the above snippet on my machine.

get dirname response

The __filename variable stores the absolute path of the current module.

The __dirname variable stores the directory name of the current module.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.