Explain it simply
Explain it simply
Compare a project to cooking a dish. package.json is the recipe card: it lists which ingredients (packages) you need, which versions, and how to cook (scripts). npm is the helper who reads the card, fetches the ingredients from the market, and stores them in a cupboard called node_modules.
With the card, nobody needs to carry the cupboard around. A friend takes the card, types npm install and buys the same ingredients themselves. package-lock.json is the receipt that records "this exact brand from this exact shop", so everyone's dish tastes the same.
Problem → Why → Solution
The problem: "it works on my machine"
You write a server with Express and push it to GitHub, leaving out node_modules because it is over 200MB. A teammate clones the repo, runs node server.js and gets "Cannot find module 'express'". Without a package.json they cannot know which packages or versions to install. If they guess and grab the latest version, it may differ from yours and bring brand-new bugs.
$ git clone https://example.com/team/shop-api.git && cd shop-api
$ node server.js
Error: Cannot find module 'express'
Require stack:
- /home/aye/shop-api/server.js
$ ls package.json
ls: cannot access 'package.json': No such file or directoryWhy is package.json needed?
The code says require('express') but not which version or where to get it. package.json records the dependency list with version ranges, and package-lock.json records the exact versions actually installed, including the dependencies of your dependencies. Commit those two files and anyone can rebuild the same environment with one command.
Core concept: three files and a handful of commands
npm init -y creates a package.json with default values in the current folder (-y skips the questions and accepts the defaults). You get fields such as name, version, main and scripts, and recent npm versions also add "type": "commonjs"; change it to "module" if you want ES modules.
npm install express downloads the package from the npm registry into node_modules, along with every package express itself needs. It then adds an entry such as "express": "^5.1.0" to dependencies in package.json and updates package-lock.json. npm install --save-dev eslint (or -D) puts the package under devDependencies instead, for tools needed only during development, such as test runners, linters and build tools. Anything the app requires or imports while it runs must be in dependencies.
Version numbers follow semver: MAJOR.MINOR.PATCH. PATCH is a bug fix, MINOR adds backward-compatible features, and MAJOR may break your code. ^5.1.0 means "5.1.0 or later, but below 6.0.0", and ~4.1.0 means "4.1.0 or later, but below 4.2.0". Because of these ranges, one package.json can match many versions; package-lock.json is what pins the versions you actually tested.
| Command | What it does |
|---|---|
| npm install | Install everything listed, updating the lock if needed |
| npm ci | Exact lock-file install into a fresh node_modules |
| npm run dev | Run scripts.dev |
| npm start / npm test | Shortcuts that need no run |
| npx <tool> | Run a package's command without a global install |
When npm runs a script it temporarily puts node_modules/.bin on the PATH. That is why a script like "lint": "eslint ." works with the project's own eslint even though it was never installed globally.
- package.json: what you need + ranges
- package-lock.json: exact versions
- node_modules: the downloaded code
- Commit the first two, never the third
You can delete node_modules at any time; npm install (or npm ci) rebuilds it.
General pattern
npm init -y # create package.json
npm install <package> # runtime dependency
npm install --save-dev <tool> # development-only tool (-D)
npm uninstall <package> # remove it again
npm run <script-name> # run an entry from "scripts"
npm ci --omit=dev # exact, production-only installThese few commands cover most of a project's life. Replace <package> with a name such as express or zod; you can also pin a major version, as in express@5.
Example: reading a package.json
npm commands need the network and the disk, so this example holds what package.json might look like after npm init -y and a few installs, as a plain JavaScript object, and reads it. It prints the command for each script and which top-level packages get installed on a developer machine versus a production server.
npm init -y
npm install express zod
npm install --save-dev eslint
npm pkg set scripts.dev="node --watch server.js"// What package.json might contain after the commands above
const pkg = {
name: 'shop-api',
version: '1.0.0',
scripts: {
start: 'node server.js',
dev: 'node --watch server.js',
test: 'node --test',
},
dependencies: { express: '^5.1.0', zod: '~4.1.0' },
devDependencies: { eslint: '^9.0.0' },
};
console.log(`${pkg.name}@${pkg.version}`);
for (const [name, command] of Object.entries(pkg.scripts)) {
const shortcut = name === 'start' || name === 'test';
const how = shortcut ? `npm ${name}` : `npm run ${name}`;
console.log(`${how.padEnd(12)} -> ${command}`);
}
const prod = Object.keys(pkg.dependencies);
const dev = Object.keys(pkg.devDependencies);
console.log('developer machine:', [...prod, ...dev].join(', '));
console.log('production server:', prod.join(', '));Code breakdown
- scripts
dev: 'node --watch server.js',Node 22's built-in --watch flag restarts the server whenever a file changes, the job people used to install nodemon as a devDependency for.
- Version ranges
dependencies: { express: '^5.1.0', zod: '~4.1.0' },express may be any 5.x.x from 5.1.0 up, while zod is limited to 4.1.x. npm install writes the ^ form by default.
- start and test shortcuts
const shortcut = name === 'start' || name === 'test';start and test have built-in shortcuts, so they need no run; any other script, such as dev, is invoked as npm run dev.
- Production install
console.log('production server:', prod.join(', '));npm ci --omit=dev skips devDependencies, so eslint never reaches the production server. These are only the top-level packages; their own dependencies are installed too.
shop-api@1.0.0
npm start -> node server.js
npm run dev -> node --watch server.js
npm test -> node --test
developer machine: express, zod, eslint
production server: express, zodVersion ranges up close
| Range | Allows | Rejects |
|---|---|---|
| ^5.1.0 | 5.1.0, 5.4.2, 5.99.0 | 5.0.9, 6.0.0 |
| ~4.1.0 | 4.1.0, 4.1.7 | 4.2.0 |
| ^0.2.3 | 0.2.3, 0.2.9 | 0.3.0 |
| 1.2.3 | only 1.2.3 | everything else |
0.x versions are stricter
Before 1.0.0, a MINOR bump is treated as breaking, so ^0.2.3 stays within 0.2.x. Keep that in mind when you depend on young packages.
Local tools and npx instead of global installs
Installing a tool with npm install -g gives the whole machine a single version and leaves no record in package.json. When project A needs eslint 8 and project B needs eslint 9 they clash, and teammates cannot tell what to install. Installing the tool with -D and calling it from a script, or running npx eslint ., gives every project its own version. When the package is not installed locally, npx downloads it temporarily and runs it, which suits one-off generators such as create-vite.
In real projects
Where this shows up in real projects
In team projects the scripts in package.json become the project's control panel. A newcomer's README only needs "npm install, then npm run dev". Build, lint, test and database migrations all run through commands with predictable names such as npm run build and npm run lint, so the routine is the same from project to project.
CI pipelines such as GitHub Actions, and Docker images, use npm ci instead of npm install. npm ci stops with an error when package-lock.json and package.json disagree, which immediately catches mistakes like forgetting to commit the lock file. Adding --omit=dev for the production image leaves test tools out, which shrinks the image and reduces the attack surface.
Common mistakes
Common mistakes
1. Committing node_modules to Git
node_modules holds thousands of files, and some packages are compiled for one OS, so a copy committed from Windows can break on a Linux server. Put node_modules/ in .gitignore and commit only package.json and package-lock.json.
2. Installing a runtime package with -D
Typing npm install -D express works fine locally, then the production server deployed with --omit=dev crashes with "Cannot find module 'express'". Every package the app requires or imports must be in dependencies.
3. Deleting package-lock.json whenever something breaks
Deleting the lock file and reinstalling pulls the newest version in every range, so hundreds of dependencies can change at once. Update the one problem package with npm install name@version instead.
Best practices
Best practices
- Always commit package-lock.json and read its diff in pull requests.
- Before adding a package, check its weekly downloads, latest release and dependency count on the npm website.
- Run npm outdated to see stale packages and npm audit to check for known security issues.
Mini challenge
Mini challenge: write your own satisfies()
Using only plain JavaScript, write satisfies(range, version), which returns true or false depending on whether the range allows that version.
- A plain version such as '1.2.3' matches only itself
- ~ requires the same MAJOR.MINOR and at least the minimum
- ^ requires the same MAJOR and at least the minimum; for ^0.x.y the MINOR must match too
- Test eight range/version pairs and print the results
function parse(version) {
// TODO: '5.4.2' -> [5, 4, 2]
}
function compare(a, b) {
// TODO: negative if a < b, 0 if equal, positive if a > b
}
function satisfies(range, version) {
// TODO: exact match, then the '~' rule, then the '^' rule (0.x is stricter)
}
const checks = [['^5.1.0', '5.4.2'], ['^5.1.0', '6.0.0'], ['^5.1.0', '5.0.9'],
['~4.1.0', '4.1.7'], ['~4.1.0', '4.2.0'], ['^0.2.3', '0.2.9'],
['^0.2.3', '0.3.0'], ['1.2.3', '1.2.3']];
// TODO: print "<range> <version> <true|false>" for each pairExpected: Expected output: ^5.1.0 5.4.2 true ^5.1.0 6.0.0 false ^5.1.0 5.0.9 false ~4.1.0 4.1.7 true ~4.1.0 4.2.0 false ^0.2.3 0.2.9 true ^0.2.3 0.3.0 false 1.2.3 1.2.3 true
Show hint
Check range[0]: if it is neither '^' nor '~', treat the range as an exact version. compare() only needs the first differing number among indexes 0 to 2.
Show solution
function parse(version) {
return version.split('.').map(Number);
}
function compare(a, b) {
for (let i = 0; i < 3; i++) {
if (a[i] !== b[i]) return a[i] - b[i];
}
return 0;
}
function satisfies(range, version) {
const v = parse(version);
const op = range[0];
if (op !== '^' && op !== '~') return compare(v, parse(range)) === 0;
const min = parse(range.slice(1));
if (compare(v, min) < 0) return false;
if (op === '~') return v[0] === min[0] && v[1] === min[1];
if (min[0] > 0) return v[0] === min[0];
return v[0] === 0 && v[1] === min[1];
}
const checks = [['^5.1.0', '5.4.2'], ['^5.1.0', '6.0.0'], ['^5.1.0', '5.0.9'],
['~4.1.0', '4.1.7'], ['~4.1.0', '4.2.0'], ['^0.2.3', '0.2.9'],
['^0.2.3', '0.3.0'], ['1.2.3', '1.2.3']];
for (const [range, version] of checks) {
console.log(`${range.padEnd(7)} ${version.padEnd(6)} ${satisfies(range, version)}`);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- package.json lists the packages and scripts you need; package-lock.json records the exact versions installed.
- Runtime packages go in dependencies; development tools go in devDependencies via -D.
- ^ fixes the MAJOR and ~ fixes MAJOR.MINOR; everything after may grow.
- Never commit node_modules, and use npm ci in CI and production.
npm package.json — npm