DEV Community

Cover image for FIX "ReferenceError: __dirname is not defined in ES module scope" in NodeJs.
Stanley
Stanley

Posted on

2 1

FIX "ReferenceError: __dirname is not defined in ES module scope" in NodeJs.

'__dirname' is used to get the directory name of the currently executing module's file.
Let's first try to understand why this error is flagged. This error occurs because __dirname is not available as a global variable in ES6 (ECMAScript 2015) module scope. In ES6 modules, the global scope is encapsulated, and certain variables that were available in CommonJS modules (like __dirname and __filename) are not automatically available in ES6 modules. Remember that there are two types of module systems, CommonJS and ES6 module systems.
To Fix this Error, we can use the following alternative method:

      import { dirname } from 'path';
      import { fileURLToPath } from 'url';

      const __filename =fileURLToPath(import.meta.url);
      const __dirname = dirname(__filename);
Enter fullscreen mode Exit fullscreen mode

By following this approach, you can access the equivalent of __dirname in ES6 modules without encountering the "ReferenceError".

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more