Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 133 ยท Modules and Packages

CommonJS Modules

Understand CommonJS in Node.js - require, module.exports vs exports, the module wrapper, require.cache, require.resolve, JSON files, circular requires and when to still use it.

Before JavaScript had a module system, Node.js invented one. It is called CommonJS (CJS): a file assigns what it wants to share to module.exports, and other files call require() to get it. For more than a decade every Node.js program, and nearly every package on npm, used it. Today new code should use ES modules, but CommonJS has not gone away. Old projects, many tools and plenty of npm packages still use it, and a lot of Stack Overflow answers show require. You need to read it fluently.

CommonJS is also a good way to learn how modules work at all, because it is so simple that you can rebuild the core of it in a few lines, which is exactly what we do in this lesson.

Our editor runs examples as ES modules by default. To run a snippet as CommonJS, make its first line the comment // cjs. Then the file is main.cjs, and require, module, exports, __dirname and __filename all exist. Every example below starts with that line.

require and module.exports

Each file is a module. Whatever you assign to module.exports is what require() hands back to the file that asked for it. Everything else in the file stays private.

Node.js A first CommonJS module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice what require returns: the exact object that was assigned to module.exports. Here that is a plain object with one function. A module can export anything: a function, a class, a single value, or an object with many members.

JavaScript
module.exports = function parse(text) { /* ... */ };   // one function
module.exports = class Cache { /* ... */ };            // one class
module.exports = { parse, format, VERSION: '1.0' };    // several things

Unlike import, require() is an ordinary function call. It runs when the line runs, it can be inside an if or a function, and its argument can be a computed string. It is also synchronous: it reads and runs the file before returning. That simplicity is the reason CommonJS cannot support top-level await.

exports versus module.exports

There are two names for the export object, and mixing them up is the most famous CommonJS trap. When a module starts, exports and module.exports point at the same empty object. So you can add properties through either name. But require() always returns module.exports. If you reassign exports, you only change a local variable, and the real export is untouched.

Node.js Why reassigning exports does nothing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The three results tell the story. Adding properties to exports works. Reassigning exports leaves module.exports as the original empty object, so require gives you {}. In mixed.cjs, the line module.exports = { second: ... } swaps in a brand new object, and the earlier and later assignments to exports went to the old one.

Rule of thumb: use exports.name = value for several named things, module.exports = something for one thing, and never mix them in the same file.

The module wrapper

Where do require, module, exports, __dirname and __filename come from? They are not globals. Before running a CommonJS file, Node wraps its source in a function and calls it with those five values as arguments:

JavaScript
(function (exports, require, module, __filename, __dirname) {
  // your file's code goes here
});

This explains several behaviours at once. Your top-level const and function declarations are local to that function, so files do not leak variables into each other. A top-level return is legal in CommonJS. And this at the top level is module.exports. You can see the wrapper's arguments through the arguments object.

Node.js Peeking at the wrapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

require.main === module is true only in the file you started from. It is the classic CommonJS way to write "run this only when executed directly, not when imported": if (require.main === module) main();. The ESM equivalent compares import.meta.url with the entry point, as shown in Running Node.

The module cache

The first time a file is required, Node runs it. After that, require returns the cached module.exports and does not run the file again. That makes modules natural singletons: two files requiring the same database module share one connection object.

Node.js Modules run once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The message prints once, then both variables are the very same object and share the counter. require.cache maps absolute file paths to module records; deleting an entry forces the next require to execute the file again. This is how some tools implement hot reloading, but it is fragile: modules that already hold a reference to the old export keep using it, so use it only in tests and dev tools.

require.resolve('./once.cjs') returns the absolute path Node would load without loading anything. It is handy as the key for the cache and for checking whether an optional dependency is installed.

How require finds a module

require(specifier) follows an algorithm that depends on what the specifier looks like.

Specifier What Node does
node:fs or fs Loads the built-in module (prefer the node: form)
./file, ../lib/x, /abs/path Loads a file relative to the current one
lodash (bare name) Looks for node_modules/lodash in the current folder, then each parent folder up to the root

Unlike ES modules, require guesses extensions. For require('./data') it tries data exactly, then data.js, data.json, data.node, and then treats data as a folder and looks for its package.json main or an index.js. That convenience is handy but ambiguous, so many style guides recommend writing the extension anyway.

When nothing matches, you get a MODULE_NOT_FOUND error, which also lists the stack of files that were being loaded:

Node.js A module that does not exist (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The caught error has the code MODULE_NOT_FOUND. The final uncaught require ends the program with a stack trace, because no npm packages are installed in our editor. In a real project this error usually means you forgot npm install, or a dependency is missing from package.json.

Requiring JSON

require also loads .json files, parsing them into plain objects. The result is cached like any module, so every caller gets the same object, and a change made by one is visible to all.

Node.js Requiring a JSON file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This is fine for static configuration that never changes. For data that changes while the program runs, read the file with fs and parse it yourself; require would keep serving the stale cached copy.

Circular requires

If a.cjs requires b.cjs while b.cjs also requires a.cjs, Node does not loop forever. The second require returns whatever module.exports of the unfinished module contains at that moment, a partially filled export object.

Node.js Partial exports in a cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

b.cjs received an object with only early, because a.cjs had not reached its late line yet. Two lessons follow. First, put exports.x = ... before any require that might lead back to you, or better, restructure to remove the cycle (see Module Design Patterns). Second, if a module does module.exports = {...} after the cyclic require, the other side keeps the old, abandoned object forever.

CommonJS meets ES modules

From Node 22.12 on, require() can load an ES module synchronously as long as that module does not use top-level await. The result is the module namespace object:

Node.js require() of an ES module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The namespace has an extra __esModule key because the module has a default export; Node adds it so that code compiled from TypeScript or Babel can recognise the shape. The other direction has always worked: a CommonJS file can call import('./esm.mjs'), which returns a promise, and an ES module can import a CommonJS file and gets module.exports as its default export. The details and pitfalls are in Mixing ESM and CommonJS.

Should you still write CommonJS?

For new code, prefer ES modules: they are the standard, work in browsers, support top-level await, and allow static analysis (tools can tell which exports are unused). Write CommonJS when you maintain an existing CommonJS code base, when a tool or config file format requires it (some tools still look for .cjs files), or when you need a quick script and prefer __dirname and require. The skills transfer: the module cache, singletons and partial exports behave similarly in both systems.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file runs exports = { a: 1 }; and nothing else. What does require() of that file return?

    Reassigning exports only changes a local variable. require() always returns module.exports, which is still the original empty object.
  2. 2. What is the module wrapper?

    Node wraps each CommonJS file in a function with five parameters. That is why top-level variables stay private and why those names exist without being globals.
  3. 3. A module is required from three different files. How many times does its top-level code run?

    require.cache stores the module after its first execution, so later require() calls return the same exports object without running the file again.
  4. 4. In a circular require between a.cjs and b.cjs, what does the second module receive from the first?

    Node returns the unfinished module's current module.exports to break the cycle. Anything assigned later is not visible to that early require.
  5. 5. How do you run a snippet as CommonJS in this tutorial's editor?

    A first line of // cjs makes the editor save the code as main.cjs, so require, module and __dirname exist.

Summary

  • CommonJS is Node's original module system: module.exports shares, require() loads, and it is synchronous.
  • exports and module.exports start as the same object, but require returns module.exports, so never reassign exports.
  • Node wraps each file in a function with exports, require, module, __filename and __dirname; top-level this is module.exports.
  • Modules run once and are cached in require.cache; require.resolve finds the path without loading.
  • require resolves built-ins, relative paths (guessing .js, .json, index.js) and bare names via node_modules; failures give MODULE_NOT_FOUND.
  • Required JSON is parsed once and shared; circular requires return partial exports.
  • Node 22.12 and later can require() an ES module that has no top-level await.
  • Prefer ES modules for new code, but read and maintain CommonJS confidently.

Next: Mixing ESM and CommonJS shows how the two systems work together and where they clash.