Modules
A real program isn't one giant file. Node's module system — require() to pull code in, module.exports to make it available — is how you split logic across files and reuse it.
Exporting from a module
Whatever you attach to module.exports is what another file gets back when it requires this one:
JS math.js
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = { add, multiply };
Requiring a module
JS index.js
const math = require("./math");
console.log(math.add(2, 3));
console.log(math.multiply(4, 5));
bash terminal
node index.js
Output
5 20
The ./ in front of ./math is what tells Node this is a local file rather than an installed package — require("./math") resolves to math.js in the same folder, and the .js extension can be left off.
Requiring built-in and third-party modules
Node's own built-in modules and anything installed via npm are required by name, with no ./:
JS example.js
const path = require("path");
console.log(path.join("folder", "file.txt"));
Output
folder/file.txt
Note: a module's top-level code only runs once, the first time it's required — Node caches the result. If three different files
require("./math"), they all get the exact same object back, not three fresh copies. This matters if a module keeps any internal state.