CommonJS Modules

Export values with module.exports and load them with require.

Syntaxmodule.exports = value; const value = require('./file');

CommonJS is Node's original module system. You export values from a file with module.exports and load them elsewhere with require().

How require finds a module

When you call require('x'), Node checks whether x is a core module, then a relative path, then walks up looking inside node_modules folders.

How require resolves a module namerequire('x')Is it a core module?fs, http, path... yes then loadStarts with ./ or ../ ?load that local fileLook in node_moduleswalk up folders until found
require checks core modules, then local paths, then node_modules.

Example

Example · javascript
// math.js
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
module.exports = { add, subtract };

// app.js
const math = require('./math');
console.log(math.add(2, 3));      // 5
console.log(math.subtract(9, 4)); // 5

When to use it

  • A legacy Node.js API server uses `require()` and `module.exports` throughout because it predates ES module support in Node.
  • A Jest test suite runs without extra config because Jest natively understands CommonJS `require()` without a build step.
  • A monorepo's shared utilities package uses CJS so it can be consumed by both older Node services and newer ESM code via dynamic `import()`.

More examples

module.exports object pattern

Exports a configuration object using CJS `module.exports` and imports it in another file.

Example · js
// config.js
const config = {
  port: process.env.PORT || 3000,
  env: process.env.NODE_ENV || 'development',
};
module.exports = config;

// server.js
const config = require('./config');
console.log('Port:', config.port);

Named exports with exports shorthand

Uses the `exports` shorthand to attach multiple named functions to the module.

Example · js
// utils.js
exports.square = (n) => n * n;
exports.cube   = (n) => n * n * n;

// main.js
const { square, cube } = require('./utils');
console.log(square(4)); // 16
console.log(cube(3));   // 27

Lazy require inside a function

Places `require()` inside a function body so the module is loaded only when the function is first called.

Example · js
// Delay loading a heavy module until it's actually needed
function generateReport(data) {
  const PDFKit = require('pdfkit'); // loaded only on first call
  const doc = new PDFKit();
  doc.text(JSON.stringify(data));
  return doc;
}

Discussion

  • Be the first to comment on this lesson.