Modules and npm
Split your code into pieces, then borrow code the whole world has written
require/module.exports (or import/export). And npm lets you download ready-made modules other people wrote, so you do not have to build everything yourself.
- split code into files with
module.exportsandrequire, - use the modern
import/exportstyle, - create a
package.jsonand install packages withnpm install.
1. What is a module?
In Node.js, every file is a module. A module keeps its own code private unless it chooses to export something. Another file can then require (import) what was exported.
Analogy: think of a toolbox. Each drawer (module) holds a few tools. When you build something you open only the drawers you need. You do not dump every tool onto the floor at once. Modules keep your project tidy, so each file does one job well.
2. Exporting and requiring (CommonJS)
The classic Node style is called CommonJS. You share code by putting it on module.exports, and you bring it in with require(). Local files use a path that starts with ./ (the current folder).
First, a module that exports two functions:
// math.js — a module that exports two helpers
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };
Now another file uses it. require('./math') gives back exactly the object we exported:
// app.js — uses the math module
const math = require('./math');
console.log(math.add(2, 3)); // 5
console.log(math.subtract(10, 4)); // 6
Run it in the terminal and you see:
$ node app.js
5
6
You can also export a single value directly by replacing the whole module.exports:
// greet.js — exports ONE thing directly
module.exports = function greet(name) {
return 'Hello, ' + name + '!';
};
// app.js
const greet = require('./greet');
console.log(greet('Sara')); // Hello, Sara!
Notice you leave the .js off in require('./greet') — Node adds it for you.