Modules and npm

CommonJS modules

Use require and module.exports in projects that use Node’s original module system.

CommonJS is Node’s original module system. You load a module with require() and expose values through module.exports.

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

module.exports = { add }

// app.cjs
const { add } = require('./math.cjs')
console.log(add(2, 3)) // 5

Run node app.cjs and you get 5. The ./ tells Node to look beside the requiring file, not in the current working directory.

Node wraps each CommonJS file in a function. That gives the module its own top-level scope and the local values require, module, exports, __filename, and __dirname. Variables declared in math.cjs do not become globals.

Relative requests such as ./math.cjs resolve from the requiring file. Package requests such as require('fastify') resolve through node_modules. The node: prefix makes a built-in explicit:

const { readFile } = require('node:fs')

The value returned by require() is module.exports. The exports variable starts as a shortcut to that same object, so this works:

exports.add = add

Reassigning the shortcut does not work:

exports = { add } // require() still receives the old module.exports

Assign a replacement value to module.exports instead.

CommonJS modules are cached by resolved filename after the first load. Requiring the same file again normally returns the same exported object without rerunning its top-level code. That is useful for shared state but makes import-time side effects harder to test. Export a function when work should happen on every call.

Use .cjs for an explicit CommonJS file. A .js file is also CommonJS when the nearest package.json declares "type": "commonjs". Being explicit avoids tools guessing wrong. Package managers, test runners, and bundlers all read that field.

Try this on your own: add a top-level console.log() to math.cjs, require it twice from app.cjs, and notice the message prints once. Then reproduce the exports = { add } mistake and fix it with module.exports.

Lesson completed