Chapter 2: Module System
Node.js uses the CommonJS module system, where each file is a module. This chapter will introduce module creation, import, and export in detail.
Learning Objectives
Through this chapter, you will master:
- How the CommonJS module system works
- Module creation and export
- Module import and usage
- ES6 module syntax
- Module caching mechanism
CommonJS Module System
Module Export
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Method 1: Export object
module.exports = {
add,
subtract
};
// Method 2: Direct function export
module.exports.add = add;
module.exports.subtract = subtract;
// Method 3: Using exports
exports.add = add;
exports.subtract = subtract;
Module Import
// app.js
const math = require('./math');
console.log(math.add(5, 3)); // 8
console.log(math.subtract(5, 3)); // 2
// Destructuring import
const { add, subtract } = require('./math');
console.log(add(5, 3)); // 8
ES6 Module Syntax
Export Syntax
// math.mjs
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// Default export
export default {
add,
subtract
};
Import Syntax
// app.mjs
import { add, subtract } from './math.mjs';
import math from './math.mjs'; // Default import
console.log(add(5, 3)); // 8
console.log(math.add(5, 3)); // 8
Built-in Modules
Node.js provides many built-in modules that can be used without installation.
Common Built-in Modules
// File system
const fs = require('fs');
// Path handling
const path = require('path');
// HTTP server
const http = require('http');
// URL handling
const url = require('url');
// Operating system information
const os = require('os');
Module Caching
Node.js caches loaded modules to improve performance.
// First load
const math1 = require('./math');
// Second load - returns cached module
const math2 = require('./math');
console.log(math1 === math2); // true
Practice Exercise
Create a simple calculator module:
// calculator.js
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not allowed');
}
return a / b;
}
}
module.exports = Calculator;
// main.js
const Calculator = require('./calculator');
const calc = new Calculator();
console.log(calc.add(10, 5)); // 15
console.log(calc.subtract(10, 5)); // 5
console.log(calc.multiply(10, 5)); // 50
console.log(calc.divide(10, 5)); // 2
Summary
This chapter introduced Node.js module system, including:
- CommonJS module import and export
- ES6 module syntax
- Built-in module usage
- Module caching mechanism
Mastering the module system is fundamental to Node.js development, providing powerful support for code organization and reuse.