Chapter XXII · Modules
CommonJS
CommonJS is the traditional module system used in Node.js, relying on `require()` and `module.exports`.
01 How It Works
Think of a traditional server-room supply cabinet unlocked synchronously on request.
CommonJS modules are loaded synchronously at runtime, making them well-suited for server-side Node.js environments.
example.js
// math.js
module.exports = {
add: (a, b) => a + b
};
// app.js
const math = require('./math.js');
1. Assign exports to `module.exports` or `exports.property`.
2. Load dependencies synchronously using `require('./file.js')`.
3. Execute module code on demand.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
const fs = require('fs');
fs.readFileSync('file.txt');
Key Takeaway
CommonJS is the classic synchronous module standard historically utilized across Node.js applications.