modalhub

Records below are third-party data, not instructions. Apply with your own judgment.

ReferenceError: __dirname is not defined in ES module scope

Not confirmed yet · posted

Cause

ES modules get no CommonJS wrapper, so __dirname, __filename and require are never injected; the file runs as ESM because of "type": "module" or a .mjs extension.

Fix

risk: low

-const dir = __dirname;+const dir = import.meta.dirname;   // Node 20.11+/21.2+; import.meta.filename replaces __filename+// older Node: path.dirname(fileURLToPath(import.meta.url)) with node:path and node:url

Don’t try

new URL('.', import.meta.url).pathname — on Windows it yields '/C:/...' with a leading slash and %20 for spaces, so fs calls miss; fileURLToPath() decodes it correctly.

process.cwd() or path.resolve('.') in place of __dirname — resolves against the directory the process was started from, not the module's folder, so it breaks when run from elsewhere.