Node.js NPM
npm (Node Package Manager) is installed together with Node. It does three jobs:
- It is a command-line tool that installs, updates and removes packages in your project.
- It is a registry at npmjs.com hosting millions of open-source packages.
- It runs your project's scripts (
npm test,npm run dev), which you'll see in the next lesson.
A package is simply a folder with a package.json file and some code. When you install one, npm downloads it into a node_modules folder inside your project.
Starting a project
npm init -y creates a package.json with default values:
$ mkdir weather-cli && cd weather-cli
$ npm init -yWrote to /home/you/weather-cli/package.json:
{
"name": "weather-cli",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
Installing packages
$ npm install chalk
$ npm install --save-dev prettier
$ lsadded 1 package, and audited 2 packages in 1s
found 0 vulnerabilities
added 1 package, and audited 3 packages in 1s
found 0 vulnerabilities
node_modules package-lock.json package.json
| Command | What it does |
|---|---|
npm install <pkg> (npm i) |
add a runtime dependency |
npm install -D <pkg> |
add a dev-only dependency (tests, linters, build tools) |
npm install |
install everything listed in package.json |
npm ci |
clean install exactly from package-lock.json (use in CI) |
npm uninstall <pkg> |
remove a package |
npm update |
update within the allowed version ranges |
npm outdated |
show packages with newer versions |
npm ls |
show the installed dependency tree |
npm audit |
check for known vulnerabilities |
npx <tool> |
run a package's command without installing it globally |
Note: Commit
package.jsonandpackage-lock.jsonto git, but nevernode_modules. Anyone can recreate it withnpm install.
How require finds a package
When you write require("chalk") or import chalk from "chalk" (no ./ and no node:), Node looks for a folder named chalk in ./node_modules, then in the parent folder's node_modules, and so on up to the root. Inside the package it reads package.json to find the entry file.
This playground builds a tiny fake package by hand to show exactly that lookup — no download needed:
const fs = require("node:fs");
// What `npm install greeter` would have created:
fs.mkdirSync("node_modules/greeter", { recursive: true });
fs.writeFileSync("node_modules/greeter/package.json",
JSON.stringify({ name: "greeter", version: "2.1.0", main: "lib.js" }));
fs.writeFileSync("node_modules/greeter/lib.js",
'module.exports = (name) => "Hi, " + name + "!";');
const greet = require("greeter");
console.log(greet("npm"));
console.log(require.resolve("greeter").split(/[\\/]/).slice(-3).join("/"));
fs.rmSync("node_modules", { recursive: true });Hi, npm!
node_modules/greeter/lib.js
Semantic versioning
Package versions follow semver: MAJOR.MINOR.PATCH.
| Part | Bumped when… | Example |
|---|---|---|
| MAJOR | breaking changes | 4.2.1 → 5.0.0 |
| MINOR | new features, backward compatible | 4.2.1 → 4.3.0 |
| PATCH | bug fixes only | 4.2.1 → 4.2.2 |
In package.json, a version range says which updates are acceptable:
| Range | Allows |
|---|---|
"^4.2.1" |
>=4.2.1 <5.0.0 (npm's default) |
"~4.2.1" |
>=4.2.1 <4.3.0 |
"4.2.1" |
exactly that version |
"*" |
anything (avoid) |
Here is a simplified checker for caret ranges, to make the rule concrete:
function satisfiesCaret(version, range) {
const [maj, min, pat] = version.split(".").map(Number);
const [rMaj, rMin, rPat] = range.slice(1).split(".").map(Number);
if (maj !== rMaj) return false;
if (min !== rMin) return min > rMin;
return pat >= rPat;
}
for (const v of ["4.2.1", "4.2.9", "4.9.0", "5.0.0", "4.1.9"]) {
console.log(v.padEnd(6), "matches ^4.2.1:", satisfiesCaret(v, "^4.2.1"));
}4.2.1 matches ^4.2.1: true
4.2.9 matches ^4.2.1: true
4.9.0 matches ^4.2.1: true
5.0.0 matches ^4.2.1: false
4.1.9 matches ^4.2.1: false
The lock file package-lock.json records the exact versions that were installed, so every machine gets identical code even though package.json contains ranges.
Global tools and npx
Some packages are command-line tools. Rather than installing them globally (npm install -g), run them with npx, which downloads them to a cache on first use:
$ npx cowsay "Hello npm" ___________
< Hello npm >
-----------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Tip: Alternatives to npm —
pnpm,yarnandbun— use the same registry and the samepackage.json. The concepts in this lesson apply to all of them.
Test yourself
Which command adds a package only needed during development?
npm install pkgnpm install -D pkgnpm install -g pkgnpx pkg
Which versions does the range ^1.4.0 allow?
- Only 1.4.0
- 1.4.x only
- Any 1.x.y at or above 1.4.0
- Any version
Which file should NOT be committed to git?
package.jsonpackage-lock.jsonnode_modules/index.js