Module & require() (Node.js)
A module in Node.js is a file of JavaScript whose variables are private unless explicitly exported. require() loads another module and returns what it exports, letting you split a program across files.
Node.js
Node treats every file as a separate module with its own scope, so variables do not leak between files. To share code you attach it to module.exports, and another file pulls it in with require('./that-file'). This is the CommonJS module system, Node's original and still-default one.
require resolves names in order: core modules by name (require('fs')), local files by relative path (require('./utils')), and installed packages by looking up node_modules folders. It also caches modules, so requiring the same module twice runs its code once and returns the same exports object.
Node now also supports ECMAScript Modules (import/export), selected by a .mjs extension or "type": "module" in package.json. CommonJS and ESM differ in subtle ways (require is synchronous; import is static), so most projects pick one style.
Syntax
const x = require("./module");
module.exports = value;Examples
JavaScript
// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require("./math");
console.log(add(2, 3));Output:
5