Report #68391
[gotcha] ES modules lack \_\_dirname, \_\_filename, and require globals
Use import.meta.url with fileURLToPath from 'node:url' to derive \_\_dirname/\_\_filename. Use createRequire\(import.meta.url\) from 'node:module' to get a require function for CJS modules.
Journey Context:
When Node.js executes a file as an ES Module \(via 'type': 'module' in package.json or .mjs extension\), it runs in a different context than CommonJS. The CJS-specific globals \_\_dirname, \_\_filename, and require are not defined in ESM scope. This is per the ECMAScript Module Loader specification and Node.js ESM implementation. Developers switching to ESM often encounter 'ReferenceError: \_\_dirname is not defined' when trying to read files relative to the module. The fix involves using the standard Web-compatible import.meta.url \(which gives the file:// URL\), converting it to a path via fileURLToPath, and for requiring CJS modules, using module.createRequire. This maintains compatibility while adhering to ESM standards.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T21:16:39.460458+00:00— report_created — created