skip to content

Moving a Node.js 24 file from CommonJS to ESM, which CommonJS module-scope bindings disappear, and what does Node offer in place of each?

level: middleimportance: must knowfreq 58%

answer

  1. no wrapper, no wrapper variables
  2. per-file data moves to import.meta
  3. a local require on demand
  4. resolve without loading
  5. a separate ESM cache

basics

~10 s

In an ES module, require, module, exports, __filename and __dirname do not exist. Node 24 replaces them with import and export, import.meta.filename and import.meta.dirname, import.meta.resolve(), and module.createRequire(import.meta.url) when a real require is still needed.

solid answer

~40 s

CommonJS hands every file five bindings through the module wrapper; an ES module gets none of them. Exports become `export` declarations and `require()` becomes `import`. `__filename` and `__dirname` become `import.meta.filename` and `import.meta.dirname`, which are no longer experimental as of Node 24.0.0 and exist only for `file:` modules. `require.resolve()` becomes `import.meta.resolve()`, which returns a URL string synchronously, and `require.main === module` becomes `import.meta.main`, added in 24.2.0 and still early development. When you genuinely need a CommonJS `require` (a native addon, CommonJS resolution rules), `createRequire(import.meta.url)` from `node:module` builds one that resolves relative to the current file. `require.cache`, `require.extensions` and `NODE_PATH` have no ESM counterpart: the ES module loader keeps its own cache, and customization hooks replace extension handlers.

code

javascript · 10 lines
javascript
import { createRequire } from 'node:module';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';

const require = createRequire(import.meta.url);
const legacy = require('./legacy-config.cjs');

const schema = await readFile(join(import.meta.dirname, 'schema.sql'), 'utf8');
console.log(import.meta.filename, require.resolve('./legacy-config.cjs'));
console.log(Object.keys(legacy), schema.length);

go deeper

for a junior

Remember the two you will use daily: import.meta.dirname replaces __dirname and import.meta.filename replaces __filename, both on Node 24.

for a middle

Walk through each wrapper binding and its ES module replacement, and explain why import.meta.url needs fileURLToPath before path functions.

for a senior

Point out what has no replacement, require.cache above all, and how that breaks reload-based tests and hot reload during a migration.

for a principal

Decide where createRequire is allowed: a narrow escape hatch for addons and CommonJS resolution, not a shim that keeps the codebase half-converted.

## Why the bindings vanish A **CommonJS** file in Node runs inside a function wrapper, and that wrapper's parameters are where `require`, `module`, `exports`, `__filename` and `__dirname` come from. An **ES module** is not wrapped: it is a module record that the ES module loader links and evaluates, and its per-file information lives on the `import.meta` object instead. So converting a file (renaming it to `.mjs`, or setting `"type": "module"`) removes all five bindings at once; calling or reading one throws a `ReferenceError` at run time. ## The replacement for each binding | CommonJS | Node 24 ES module equivalent | Note | |---|---|---| | `require('x')` | `import ... from 'x'`, or `await import('x')` | static imports are hoisted and linked first | | `module.exports`, `exports.x` | `export default`, `export const x` | export declarations replace object mutation | | `__filename` | `import.meta.filename` | absolute path, symlinks resolved | | `__dirname` | `import.meta.dirname` | same as `path.dirname(import.meta.filename)` | | `require.resolve('x')` | `import.meta.resolve('x')` | returns a URL string, not a path | | `require.main === module` | `import.meta.main` | added in 24.2.0, early development | | `require('./data.json')` | `import data from './data.json' with { type: 'json' }` | the attribute is mandatory | | `require.cache` | none | the ES module loader has its own cache | | `require.extensions` | customization hooks | a separate subject | Points worth knowing about the replacements: - `import.meta.filename` and `import.meta.dirname` were added in 20.11.0 and 21.2.0 and are no longer experimental in Node 24.0.0. They exist only on `file:` modules, so a module loaded from a `data:` URL has neither. - `import.meta.url` has existed for much longer, but it is a `file:` URL string. Passing it to `path.join` produces a broken path; convert it with `url.fileURLToPath()` or use the two properties above. - `import.meta.resolve()` runs Node's full resolution, including a package's `exports` rules, and returns synchronously. Like `require.resolve`, it can touch the file system synchronously. - The two resolvers are not interchangeable. `import.meta.resolve()` resolves as an `import` would and `require.resolve()` as a `require()` would, so for a package that maps `import` and `require` to different files the two can return different targets. Pick the one that matches how the file will actually be loaded. - Replacing a synchronous `require()` deep inside a function with `await import()` makes that function asynchronous, and with it every caller. That ripple is the most common reason teams keep a `createRequire` call during a migration. ## createRequire: a real require inside ESM `module.createRequire(filename)` from `node:module` returns an ordinary CommonJS `require` function anchored at the path you give it: 1. Pass a `file:` URL or an absolute path, normally `import.meta.url`. A relative string such as `'./'` throws `ERR_INVALID_ARG_VALUE`. 2. The function resolves specifiers relative to that file and searches `node_modules` upward from its directory, with CommonJS rules such as extension searching and folder `index.js` files. 3. It carries `require.resolve` and `require.cache` like any CommonJS `require`. Typical reasons to reach for it: - loading a native addon (`.node`), which `import` does not support without an experimental flag; - reusing a CommonJS-resolution helper during a migration; - keeping a dynamic, synchronous load where `await import()` would force the caller to become async. In Node 24 that `require` can also load a synchronous ES module, because `require()` of ESM is supported; it fails only for graphs that contain top-level `await`. ## What has no replacement - **`require.cache`.** ES modules are cached by URL in the ES module loader, which `require.cache` does not reach, and Node offers no public API to evict an ES module. A second `import()` of the same URL returns the same instance; a different query string (`./config.js?v=2`) creates a separate instance, which is how some test setups force a fresh copy. - **`NODE_PATH`.** It is ignored by `import`; the docs suggest symlinks instead. - **`require.extensions`.** Replaced by module customization hooks. ## A migration checklist 1. Replace every `__dirname`-relative path with `import.meta.dirname`. 2. Replace JSON `require` calls with import attributes, or keep them behind `createRequire`. 3. Find code that clears `require.cache` (tests, hot reload) and redesign it before the switch. 4. Keep `createRequire` for the few loads that truly need CommonJS behaviour, not as a blanket shim.

  • Why does createRequire('./') throw, and what should you pass instead?
    `createRequire` needs a `file:` URL or an absolute path; a relative string is rejected with `ERR_INVALID_ARG_VALUE`, because there would be nothing to resolve it against. Pass `import.meta.url` (or `import.meta.filename`). The returned `require` then resolves relative to the current file and searches `node_modules` upward from its directory.
  • A test helper deletes require.cache entries to reload a module between tests. What happens to that trick once the module is ESM?
    It stops working. ES modules live in the ES module loader's own cache, keyed by URL, which `require.cache` does not touch, and Node exposes no public API to evict one. Another `import()` of the same URL returns the same instance. Options are to design the module so state is created by a function, or to import with a distinct query string, which loads a separate instance.

  • import.meta.dirname also works inside a CommonJS file.
  • createRequire accepts a relative path such as './'.
  • Deleting an entry from require.cache reloads an ES module.
  • __dirname is still defined in an .mjs file.
  • import.meta.url is a plain file system path you can pass to path.join.

Assumes Node.js 24; import.meta.dirname and import.meta.filename lost their experimental status in v24.0.0, and import.meta.main was added in v24.2.0.