tezvyn:

CommonJS: Node.js's Original Module System

AI-drafted, machine-checkedSource: nodejs.orgbeginner

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.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.