npm and package.json in JavaScript
Introduction
npm manages project metadata, dependencies, and scripts through package.json. Almost every Node project starts with npm init and adds libraries with npm install. This chapter explains the manifest file, semver ranges, and common scripts you run daily.
Prerequisites
- Node.js overview
- Terminal basics from install chapters
Create a Project
mkdir hello-node && cd hello-node
npm init -yGenerates package.json:
{
"name": "hello-node",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node index.mjs"
}
}Install Dependencies
# Production dependency
npm install express
# Development-only (tests, linters)
npm install --save-dev vitestCreates node_modules/ and updates package.json + package-lock.json.
Scripts
{
"scripts": {
"start": "node index.mjs",
"dev": "node --watch index.mjs",
"test": "vitest run"
}
}npm run dev
npm testnpm start runs the start script without run.
Semver Ranges (Brief)
{
"dependencies": {
"express": "^4.21.0",
"lodash": "~4.17.21"
}
}^— compatible within same major (most common)~— patch-level updates only
Commit package-lock.json so teammates get reproducible installs.
node_modules and .gitignore
Do not commit node_modules/—it is rebuilt from the lockfile. Add to .gitignore:
node_modules/
.envnpx — Run Binaries
# One-off command from a package
npx cowsay "hello"Downloads temporarily if not installed locally.
Mini Example: Minimal API Project Layout
hello-node/
package.json
index.mjs
lib/
routes.mjs// index.mjs
import { createServer } from "node:http";
const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("ok\n");
});
server.listen(3000, () => console.log("http://127.0.0.1:3000"));npm startFAQ
npm vs yarn vs pnpm?
All manage package.json; teams pick one—npm is default with Node.
Global install?
npm install -g pkg—use sparingly; prefer local project deps and npx.
Security audits?
npm audit reports known vulnerabilities—fix or document accepted risk.