Node.js theorytheory 0/50 · 0%
Modules · easy

3. CommonJS modules

require, module.exports and how Node resolves files.

Node's original module system is CommonJS: each file is its own module, and you export things with `module.exports` (or the shorthand `exports.foo = ...`) and pull them in with `require`.

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

// index.js
const { add } = require("./math");
console.log(add(2, 3));

`require` is synchronous and cached: the first call executes the module and caches its `exports`; every later `require` of the same path returns the cached object instantly, so top-level module code runs exactly once no matter how many files import it.

Node resolves bare specifiers like `require("lodash")` by walking up `node_modules` directories, and relative specifiers like `require("./math")` relative to the current file.

Check your understanding

  1. 1. How many times does a CommonJS module's top-level code run if required from five files?

  2. 2. Is `require` synchronous or asynchronous?

  3. 3. How do you export a single function named `add`?