Lesson 4 / 28
CommonJS Modules
require and module.exports — Node's original module system.
module.exports
Each file is its own module. Expose values with module.exports.
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };require()
Pull a module in with require — Node caches it after the first load.
// app.js
const { add } = require("./math");
console.log(add(2, 3));
Output:
5
Synchronous by nature
require loads modules synchronously — fine for local files, but that's one reason ES modules were introduced.