Labs ICT
โญ Pro Login

CommonJS Modules

require and module.exports โ€” how Node.js organizes code.

Node.js needs a way to organize code across files. Before JavaScript had a module system, Node.js created CommonJS. It uses require() and module.exports.

Exporting from a Module

// math.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = { add, subtract };

Importing a Module

// app.js
const math = require("./math");

console.log(math.add(2, 3));       // 5
console.log(math.subtract(5, 2));  // 3

// Destructure on import
const { add, subtract } = require("./math");

How require() Works

When you call require(), Node.js does this:

  1. Checks if it is a core module (fs, path, http) โ€” if yes, returns it.
  2. Checks if it is a file path โ€” if yes, loads the file.
  3. Checks if it is a folder โ€” looks for package.json or index.js.
  4. Checks if it is an npm package โ€” looks in node_modules.

Built-in Modules

Node.js comes with powerful built-in modules:

const fs = require("fs");          // File system
const path = require("path");      // Path utilities
const http = require("http");      // HTTP server
const os = require("os");          // Operating system info
const url = require("url");        // URL parsing
const crypto = require("crypto");  // Cryptography

Key Rule: Always use const for require statements: const fs = require("fs"). Never reassign the required module โ€” it breaks caching.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

How do you import a module in CommonJS?