Modules & npm
Learn how to split your Node.js code into reusable modules and pull in thousands of open-source packages with npm.
Imagine trying to cook every meal in a kitchen the size of a closet, with all your ingredients, pots, and recipe books crammed into one drawer. Real kitchens have separate shelves and pantries — each item in the right place so you can find it instantly. Modules do the same thing for your JavaScript code. Instead of piling everything into one enormous file, you split code into focused files and connect them wherever needed. And npm (the Node Package Manager) is the giant supermarket where other developers have placed over two million ready-to-use packages on the shelf, free for you to grab.
#CommonJS — The Original Node.js Way
module.exports is a gift box
Think of every .js file as a gift box. module.exports is what you put inside the box before handing it over. When another file calls require('./yourFile'), it opens the box and gets exactly what you packed. Anything you do NOT put in the box stays private to that file — hidden from the rest of the app.
// greet.js — pack the box
function greet(name) {
return `Hello, ${name}!`;
}
function farewell(name) {
return `Goodbye, ${name}!`;
}
module.exports = { greet, farewell };// app.js — open the box
const { greet, farewell } = require('./greet');
console.log(greet('Alice'));
console.log(farewell('Alice'));#ES Modules — The Modern Standard
// mathUtils.mjs — named and default exports
// ESM uses import/export keywords from the JS spec itself.
// Enable it by naming the file .mjs, or add "type":"module" in package.json.
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
export default function square(n) { return n * n; }// main.mjs
import square, { add, multiply } from './mathUtils.mjs';
console.log(add(3, 4)); // named import
console.log(multiply(3, 4)); // named import
console.log(square(5)); // default importYou cannot mix require and import in the same file
CommonJS (require) and ESM (import) are two separate systems. A .js file using require() cannot also use import at the top level, and vice versa. Pick one style per project. For new projects, ESM is the recommended choice — it is the future of JavaScript modules.
#npm, package.json, and Installing Packages
Every Node.js project starts with a package.json — a structured recipe card that records the project's name, version, and all the packages it depends on. Create one by running npm init -y in your project folder. Then install any package with npm install <name>.
After installing, Node creates a node_modules/ folder (never edit by hand) and a package-lock.json (exact version snapshot for teammates). Add node_modules/ to your .gitignore — teammates restore it with npm install.
# Set up a new project
mkdir my-app && cd my-app
npm init -y
# Install a package (adds terminal colour)
npm install chalk// index.js — use the installed package
const chalk = require('chalk');
console.log(chalk.green('Success!'));
console.log(chalk.red.bold('Error!'));
console.log(chalk.blue('Info:'), 'server is running');You write `module.exports = { greet };` in greet.js. In another file you call `const result = require('./greet');`. What does `result` hold?
Key takeaways
- Modules let you split code into focused files and share only what you explicitly export — keeping the rest private.
- CommonJS uses require() and module.exports; ES Modules use import and export. Do not mix them in the same file.
- npm is both a CLI tool and a huge registry. package.json records dependencies; node_modules/ stores them locally.
- Run npm install <package-name> to add a library. Teammates restore everything with a plain npm install.
- Semantic versioning (MAJOR.MINOR.PATCH) and the ^ prefix in package.json keep you on safe, compatible updates automatically.
greet.js exports an object. What does this program print?
// greet.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = { greet };
// app.js
const { greet } = require('./greet');
console.log(greet('Alice'));This CommonJS import doesn't find the local file — what's wrong?
// app.js — greet.js sits in the same folder
const { greet } = require('greet');
console.log(greet('Bob'));Complete this ES Module so main.mjs can import add as a named import and square as the default import.
// mathUtils.mjs export function add(a, b) { return a + b; } export function square(n) { return n * n; }
Order these terminal commands to create a new project and install the chalk package.
npm init -y
npm install chalk
mkdir my-app && cd my-app
Create a small Node.js project using CommonJS modules.
- In mathUtils.js, export two functions:
double(n)which returns n * 2, andisEven(n)which returns true when n is even. - In index.js, require those functions and log the results of calling double(7) and isEven(4).
Bonus: run npm install chalk and colour the output — green for even results, red for odd.
Try it yourself — a starting point to build on:
// mathUtils.js
// TODO: write and export double(n) and isEven(n)
// index.js
const { double, isEven } = require('./mathUtils');
// TODO: log double(7) and isEven(4)