Node.js ESM ReferenceError: `__dirname` / `__filename` is not defined in ES module scope
CommonJS globals `__dirname` and `__filename` do not exist in `.mjs` / ESM files.
Runs locally in browser
Free · No login
Independently Verified 2026-11-25
v4.1.0
Identifier: Node.js ESM ReferenceError
Platform: Node.js
Common Root Causes:
- CommonJS globals `__dirname` and `__filename` do not exist in `.mjs` / ESM files.
Interactive Diagnostic Checklist
Verified Solutions:
- Use `import.meta.dirname` (Node 20.11+/22) or `path.dirname(fileURLToPath(import.meta.url))`.
Safe Diagnostic Command:
Check file extension and `"type": "module"`
Warning: Verify configuration changes in staging or with dry-run flags (e.g. nginx -t) before reloading production services.
Technical Explanation
CommonJS globals `__dirname` and `__filename` do not exist in `.mjs` / ESM files. Recommended diagnostic: `Check file extension and `"type": "module"``. Remediation: Use `import.meta.dirname` (Node 20.11+/22) or `path.dirname(fileURLToPath(import.meta.url))`.
Worked Examples
- Run `Check file extension and `"type": "module"`` to verify root cause before applying the remediation.
Limitations & Assumptions
- Always verify configuration changes in staging or with dry-run flags (e.g. `nginx -t`) before reloading production services.
Source References & Verification
Resource ID: err-node-dirname-is-not-defined-esm · Independently verified: 2026-11-25