CommonJS exports and require
CommonJS is one of Node.js’s two module systems. A module is a file or unit of code with its own scope and an interface for other modules. Use module.exports to expose values and require() to load them in CommonJS code. The .cjs extension makes the mode explicit.
Local practice: The proposed teaching runtime is Node.js 26.13.1 LTS. These original offline examples were executed on Node.js 22.16.0 (Linux x64); execution on the proposed baseline and in ByteMind is not yet verified. No npm dependencies are required. Use a fresh practice directory. Code blocks are static, not a browser-based Node runner.
Export and load a function
function total(quantity, cents) { return quantity * cents;}module.exports = total;In the directory containing the files above, run:
node main.cjsExpected standard output:
1200Expected exit status: 0.
How it works
require("./price.cjs") resolves a local file relative to the requiring module and returns its exported value. The module may export a function, object or other value. The first fixture exports a function directly; the second exports an object whose properties are functions. A built-in module is shipped with Node, a local module is part of your project, and an external package is a dependency installed or otherwise made available. A node: specifier explicitly identifies a built-in module. These fixtures need only local files.
Export two named properties
function subtotal(quantity, cents) { return quantity * cents; }function discount(total, centsOff) { return total - centsOff; }module.exports = { subtotal, discount };const { subtotal, discount } = require("./pricing.cjs");console.log(discount(subtotal(2, 700), 100));In the directory containing the files above, run:
node main.cjsExpected standard output:
1300Expected exit status: 0.
Common mistake
Do not omit ./ when you intend to load a sibling file. A bare name such as price uses a different resolution path and may look for a package. Do not construct require paths from untrusted input. Keep the file names and extension explicit in these fixtures.
Try it yourself
Split a delivery-fee calculation into delivery.cjs and main.cjs. Export a function accepting an integer base fee and item count. Call it for zero and two items, using a defined fixed per-item fee. Check both results.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CommonJS exports and require — knowledge check
Check your understanding of commonjs exports and require.
What does module.exports determine?
Which specifier selects the local sibling price.cjs?
Why use the .cjs extension in these examples?