Skip to content
tezvyn:
Menu

CommonJS: Node.js's Original Module System

Source: nodejs.orgEasyHow cards are made

CommonJS treats each file as a private box of code. You share tools using exports and import them with require. It's the original module system for Node.js, used to organize code into reusable pieces.

Why it exists

Before modules, JavaScript code in different files could easily clash over global variables. CommonJS was created for server-side JavaScript, like in Node.js, to provide a simple, file-based system for encapsulating code and managing dependencies without polluting the global scope.

The mental model

Imagine each file is a self-contained workshop. By default, all tools and materials (variables, functions) inside are private. To share a tool, you place it on a public shelf called exports. Another workshop can then use require to request a copy of that specific tool from your public shelf.

How it works

Node.js wraps each module file in a special function before executing it. This function provides the module with a private scope and access to special objects like require, exports, module, filename, and dirname. The require function is synchronous: it reads, compiles, and executes a module's code, then returns the module.exports object. Modules are cached after the first load, so subsequent require calls for the same module are very fast.

When to use it

Use CommonJS in traditional Node.js projects, especially those that haven't migrated to ES Modules. It's the default for files ending in .js in many configurations. It's straightforward for simple scripting and backend services where synchronous loading is acceptable and often simpler to reason about.

When not to use it

Avoid CommonJS for modern frontend development, where browsers use ES Modules (import/export). ES Modules offer static analysis benefits, better tree-shaking for smaller bundles, and support for top-level await. In new Node.js projects, consider using ES Modules (by setting "type": "module" in package.json) to align with the broader JavaScript ecosystem.

One canonical example

A utility file, math.js, exports two functions. // In math.js

const PI = 3.14159;

exports.area = (r) => PI r r; exports.circumference = (r) => 2 PI r;

A main file, app.js, imports and uses these functions. // In app.js

const math = require('./math.js');
console.log('Area:', math.area(5));
console.log('Circumference:', math.circumference(5));

Here, the PI constant remains private to math.js, while the area and circumference functions are publicly available via require.

Interview question

According to the CommonJS mental model, what is the default state of variables and functions defined within a module file?

  • a.They are shared with other modules unless explicitly marked as private.
  • b.They are private to the module unless explicitly exported.Correct
  • c.They are only accessible after being imported by another module.
  • d.They are globally accessible unless explicitly marked as private.
Why?

The card states that variables and functions inside a module are private by default and must be exported to be shared, so B is correct. A and D describe global or shared visibility and are incorrect; C is also incorrect because code remains accessible within its defining module before another module imports it.

Just read this? Test yourself on what you have been reading.

Read the original → nodejs.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on nodejs — each one lists the topics its interview covers.

See open roles