CodePark/ questions / Modules (CommonJS & ESM)
START PRACTICINGPRACTICE
Backend question · Node.js › Modules (CommonJS & ESM)

In an ES module (app.mjs) running on Node 22, what happens with console.log(__dirname)?

It throws ReferenceError: __dirname is not defined

It throws ReferenceError: __dirname is not defined. The CommonJS module wrapper adds __dirname and __filename to each file. ES modules have no such wrapper, so the name does not exist, and using it throws. It does not log undefined or a directory. Instead, use import.meta.dirname and import.meta.filename (Node 20.11+). Or build them from import.meta.url with fileURLToPath.