A real program is never one giant file. Node.js lets you split code across separate files called modules, and pull pieces from one file into another with require(). This is CommonJS — Node's original, still very common module system.
In Node.js, each .js file is automatically wrapped as a separate module. Variables and functions declared in one file are private to that file by default — another file can't see them unless the first file deliberately shares them.
Attach anything you want another file to be able to use to module.exports:
// math.js
function add(a, b) {
return a + b
}
function multiply(a, b) {
return a * b
}
module.exports = { add, multiply }Another file pulls that in with require(), giving it a path to the file (starting with ./ for "in this same folder"):
// app.js
const { add, multiply } = require('./math')
console.log(add(2, 3)) // 5
console.log(multiply(2, 3)) // 6Note there's no .js extension in the require() call — Node adds it automatically when the path doesn't already have one.
If a file only has one thing worth sharing, you can export it directly instead of wrapping it in an object:
// greet.js
module.exports = function greet(name) {
return `Hello, ${name}!`
}
// app.js
const greet = require('./greet')
console.log(greet('Priya'))Node also ships with modules already built in — you require() them by name instead of a file path, no installation needed:
const path = require('path')
console.log(path.extname('photo.png')) // '.png'The next several lessons cover the most useful of these built-in modules one at a time.
Modules are cached
Requiring the same module twice doesn't run its code twice — Node caches the result after the first require() and reuses it. This matters once you start sharing state, like a database connection, across files.