~2 min read • Updated Dec 29, 2025
1. Introduction
In Node.js, every file is a module. For example:
// foo.js
const circle = require('./circle.js');
console.log(`Area: ${circle.area(4)}`);
The module circle.js can export functions using exports or module.exports.
2. Exports and module.exports
exports: A shortcut for adding properties to the module’s output.module.exports: Allows replacing the entire module output with an object or class.
3. Enabling CommonJS
- Files with a
.cjsextension. .jsfiles when"type": "commonjs"is specified in package.json..jsfiles or files without an extension when notypefield is present.
4. Accessing the Main Module
require.main can be used to check if a file is executed directly or imported as a module.
5. Dependency Management
Node.js resolves dependencies from node_modules. Symbolic links and directory structures allow managing multiple versions of dependencies.
6. Loading ECMAScript Modules with require()
Experimental support exists for loading ES modules with require(), but limitations apply (e.g., no top-level await).
7. Caching
- Modules are cached in
require.cacheafter the first load. - This prevents re-execution of module code on subsequent imports.
8. Built-in Modules
Node.js includes built-in modules like http, fs, and crypto. Some require the node: prefix.
9. Cyclic Dependencies
When circular dependencies occur, Node.js returns a partially executed module to avoid infinite loops.
10. Files and Folders as Modules
- Files with
.js,.json, or.nodeextensions can be loaded. - Folders can act as modules if they contain a
package.jsonwith amainfield or anindex.jsfile.
11. Module Wrapper
Node.js wraps each module in a function to provide local scope and special variables like __dirname and __filename.
12. Example
// square.js
module.exports = class Square {
constructor(width) { this.width = width; }
area() { return this.width ** 2; }
};
// bar.js
const Square = require('./square.js');
const mySquare = new Square(2);
console.log(mySquare.area()); // 4
Conclusion
The CommonJS module system in Node.js is the foundation for organizing code. Using require(), exports, and module.exports, developers can build reusable modules, manage dependencies, and structure applications effectively.
Written & researched by Dr. Shahin Siami