Lesson 5 +10 XP

CommonJS Module System

CommonJS is the traditional module format introduced with Node.js. It loads modules synchronously using the require() function and exports values via module.exports or exports.

Exporting Modules


javascript
// math.js - Single export object assignment
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = {
  add,
  subtract
};
// logger.js - Exporting individual properties
exports.logInfo = (msg) => console.log("[INFO]", msg);
exports.logError = (msg) => console.error("[ERR]", msg);
⚠️ Warning

> Do NOT reassign exports = function() {}. exports is a helper pointer referencing module.exports. Reassigning exports directly breaks the link to module.exports!

Importing Modules


javascript
// app.js
const { add, subtract } = require("./math");
const logger = require("./logger");

console.log(add(10, 5)); // 15
logger.logInfo("System operational");

Module Caching & Scoping

  • Modules are cached after the first load. Subsequent calls to require('./file') return the cached export object without re-executing the file.
  • Node wraps modules in a wrapper function providing __filename, __dirname, require, module, and exports.

TL;DR

  • CommonJS uses require() and module.exports.
  • require() runs synchronously.
  • Loaded modules are cached in memory after initial resolution.