Topic 27 of 55
require
Overview
CommonJS (CJS) is the original module system for Node.js. It uses `require()` to import code and `module.exports` to export it. It is completely synchronous and runs at runtime.
Syntax
javascript
// --- math.js (Exporting) ---
function add(a, b) {
return a + b;
}
const PI = 3.14159;
// Export an object containing multiple things
module.exports = {
add,
PI
};
// --- app.js (Importing) ---
// Use destructuring to grab what you need
const { add, PI } = require('./math.js');
console.log(add(2, 3)); // 5Common Pitfalls
- `require()` is synchronous. If you `require()` a massive file, the execution of your program stops until the file is fully loaded and evaluated.
- Avoid circular dependencies (File A requires File B, and File B requires File A). CommonJS handles it, but you might receive an incomplete exported object.
Real-World Example
Requiring core modules vs third-party vs local files:
example
javascript
// 1. Core Node.js module (no path needed)
const fs = require('fs');
// 2. Third-party module from node_modules (no path needed)
const express = require('express');
// 3. Local file (MUST start with ./ or ../)
const config = require('./config/settings.js');
// If you omit the extension, Node looks for .js, .json, or .node automatically.
const db = require('../db'); // looks for ../db.js or ../db/index.js