Node.js — CommonJS
What is CommonJS?
CommonJS is the original module system for Node.js. Every file in Node is treated as a separate module, and CommonJS provides require() to import and module.exports to export.
Exporting with module.exports
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };
Importing with require()
// app.js
const math = require('./math');
console.log(math.add(3, 4)); // 7
console.log(math.subtract(10, 3)); // 7
Destructuring Imports
const { add, subtract } = require('./math');
console.log(add(5, 5)); // 10
Exporting a Single Value
// config.js
const config = {
port: 3000,
db: 'localhost',
secret: 'my-key'
};
module.exports = config;
// app.js
const config = require('./config');
console.log(config.port); // 3000
Exporting a Function
// greet.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = greet;
const greet = require('./greet');
console.log(greet('Alice')); // Hello, Alice!
How require() Works
- Resolves the file path
- Checks if the file is cached (modules are cached after first load)
- Loads and executes the file
- Returns
module.exports
// Built-in modules don't need a path
const fs = require('fs');
const path = require('path');
const http = require('http');
// Third-party modules use the package name
const express = require('express');
Module Caching
// require() caches the result — the file runs only once
const a = require('./math');
const b = require('./math');
console.log(a === b); // true — same object
Circular Dependencies
When two files import each other, Node resolves what it can:
// a.js
const b = require('./b');
module.exports = { name: 'a' };
// b.js
const a = require('./a'); // Partial export (name might be undefined)
module.exports = { name: 'b' };
Circular dependencies work but can cause subtle bugs — restructure your code to avoid them.
CommonJS vs ES Modules
| Feature | CommonJS | ES Modules |
|---|---|---|
| Syntax | require() / module.exports | import / export |
| Loading | Synchronous | Asynchronous |
| Where | Node.js native | Browser + Node.js |
| File extension | .js | .mjs or "type": "module" |
Best Practices
- Export a clear API — don't export internal helpers
- Use named exports (
module.exports = { fn1, fn2 }) over attaching toexports - Keep one module per file
- Avoid circular dependencies
- Use
__dirnameand__filenamefor path resolution
Practice
- Create a
utils.jsmodule withcapitalize()andreverse()functions - Import and use them in a separate
app.jsfile - Create a
config.jsthat exports database settings - Build a small file reader module using
fsand export areadJSON()function
Related Topics
Frequently Asked Questions about CommonJS
What is CommonJS in Node.js?
CommonJS is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn CommonJS?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn CommonJS.
Why is CommonJS important in Node.js?
CommonJS is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.