Report #100520
[bug\_fix] ReferenceError: \_\_dirname is not defined in ES module scope
When using ESM \(\`"type": "module"\`\), use \`import.meta.url\` to derive paths instead of \`\_\_dirname\`/\`\_\_filename\`. Common pattern: \`import \{ fileURLToPath \} from 'node:url'; const \_\_filename = fileURLToPath\(import.meta.url\); const \_\_dirname = path.dirname\(\_\_filename\);\`
Journey Context:
You add \`"type": "module"\` to package.json and suddenly \`const path = require\('path'\)\` and \`\_\_dirname\` explode. You first think Node is broken because \`\_\_dirname\` worked in every project before. You convert \`require\` to \`import\`, but \`\_\_dirname\` still fails. You search the error and land on the Node ESM docs: ESM modules intentionally do not define \`\_\_dirname\`, \`\_\_filename\`, or \`require\` because they are CommonJS constructs. You try \`process.cwd\(\)\` but that gives the working directory, not the source file location, so relative \`fs\` reads break. You then find the official \`import.meta.url\` approach. You import \`fileURLToPath\` from \`node:url\`, reconstruct \`\_\_dirname\`, and your \`fs.readFileSync\(path.join\(\_\_dirname, 'template.txt'\)\)\` works again. You realize the real root cause is that ESM is a different module system with a different scoping model, not just a syntax change.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-02T04:39:04.052036+00:00— report_created — created