← Back to Node.js, page 2

nodejs-0021 · Hard senior

How do you get __dirname and require in an ES module, and how do CommonJS and ESM interoperate?

In ESM use import.meta.dirname and import.meta.filename (Node 20.11 and later), or fileURLToPath(import.meta.url). Use createRequire when you need require. ESM can import CJS directly. CJS can use dynamic import(), and since Node 22.12 can also call require() on an ES module that has no top-level await.

Full answer

ESM has no __dirname, __filename or require. The replacements:

  • import.meta.url: the file URL of the current module.
  • import.meta.dirname and import.meta.filename: direct strings, added in Node 20.11 and 21.2.
  • fileURLToPath(import.meta.url) and path.dirname(...): the older, portable form.
  • createRequire(import.meta.url): returns a require function for loading CJS packages or reading JSON in the old way.

JSON in ESM: import data from './x.json' with { type: 'json' }. The import attribute is required.

Interop rules:

  1. ESM importing CJS: works. The default import is module.exports. Named imports work only when Node can detect them statically, so the safe form is the default import and then destructuring.
  2. CJS loading ESM: use await import('./x.mjs'). This returns a promise, so it only works in async code. From Node 22.12, require('./x.mjs') also works if that ESM graph has no top-level await. The result is the module namespace object.
  3. Dual packages publish both formats through the exports field, with the "import" and "require" conditions. Watch out for the dual package hazard: two copies of the same package (one CJS, one ESM) with separate state.

A migration tip: move one package at a time, start with leaf modules, and convert to ESM only when all the callers can handle it.

javascript
// Save as app.mjs
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';

console.log('dirname forms agree:', import.meta.dirname === path.dirname(fileURLToPath(import.meta.url)));
console.log('filename matches the URL:', import.meta.filename === fileURLToPath(import.meta.url));

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'interop-'));
fs.writeFileSync(path.join(dir, 'data.json'), JSON.stringify({ course: 'Node.js', hours: 12 }));
fs.writeFileSync(path.join(dir, 'util.mjs'), "export const twice = (n) => n * 2;\n");
fs.writeFileSync(path.join(dir, 'old.cjs'), "const { twice } = require('./util.mjs'); module.exports = twice(21);\n");

// 1. JSON import with the required attribute.
const data = await import(path.join(dir, 'data.json'), { with: { type: 'json' } });
console.log('json import:', data.default);

// 2. require() inside ESM through createRequire.
const require = createRequire(import.meta.url);
console.log('require of a json file:', require(path.join(dir, 'data.json')).hours);

// 3. A CommonJS file that uses require() on an ES module.
console.log('CJS requires ESM:', require(path.join(dir, 'old.cjs')));

fs.rmSync(dir, { recursive: true });

Part 3 needs Node 22.12 or later. On older versions use await import() inside the CommonJS file. Save it as app.mjs and run it with node app.mjs. Output (Node.js v24.22.1, same on two runs): dirname forms agree: true filename matches the URL: true json import: { course: 'Node.js', hours: 12 } require of a json file: 12 CJS requires ESM: 42

Key points

  • Use import.meta.dirname or fileURLToPath for paths.
  • createRequire gives require inside ESM.
  • JSON import needs the attribute with { type: 'json' }.
  • require(esm) works from Node 22.12 if there is no top-level await.
  • Dual packages can load two copies of the same code.

Common mistakes

  • Using __dirname in an ES module and getting a ReferenceError.
  • Importing JSON without the type attribute.
  • Relying on named imports from a CJS package that Node cannot analyse.
  • Publishing a package with both formats without testing both.

Follow-ups

  • What is the dual package hazard?
  • How would you migrate a large CJS code base to ESM?
  • How do bundlers treat these two formats?

Tips

  • Give the Node version for each feature. Interviewers often ask.
  • Say 'default import, then destructure' for CJS packages.
  • Mention exports conditions when asked about libraries.