The error, verbatim
Jump to the fix ↓console.log(path.join(__dirname, "data.json"));
^
ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file
extension and 'package.json' contains "type": "module".
Tested on
- Node
- 24.14.0
- Module type
- "type": "module" and .mjs
- OS
- Windows 11 Pro
Contents
The fix
Use import.meta.dirname. It’s built into Node and needs no imports:
import path from "node:path";
const dataFile = path.join(import.meta.dirname, "data.json");
console.log(import.meta.dirname); // folder of this file
console.log(import.meta.filename); // full path of this file
import.meta.dirname and import.meta.filename were added in Node 20.11. If you’re stuck on an older Node, use the classic two-line fallback:
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Why it happens
__dirname, __filename and require are not real globals. Node injects them into every CommonJS file. ES modules don’t get them, because ESM identifies files by URL (import.meta.url) rather than by path.
Your file is treated as an ES module when either of these is true:
package.jsonhas"type": "module"and the file ends in.js- the file ends in
.mjs
The error message says which one applies to you.
What didn’t work
— N.K., end of entry No.002