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

Create a Project

bash
mkdir hello-node && cd hello-node
npm init -y

Generates package.json:

json
{
  "name": "hello-node",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node index.mjs"
  }
}

Install Dependencies

bash
# Production dependency
npm install express
 
# Development-only (tests, linters)
npm install --save-dev vitest

Creates node_modules/ and updates package.json + package-lock.json.

Scripts

json
{
  "scripts": {
    "start": "node index.mjs",
    "dev": "node --watch index.mjs",
    "test": "vitest run"
  }
}
bash
npm run dev
npm test

npm start runs the start script without run.

Semver Ranges (Brief)

json
{
  "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:

plaintext
node_modules/
.env

npx — Run Binaries

bash
# One-off command from a package
npx cowsay "hello"

Downloads temporarily if not installed locally.

Mini Example: Minimal API Project Layout

plaintext
hello-node/
  package.json
  index.mjs
  lib/
    routes.mjs
javascript
// 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"));
bash
npm start

FAQ

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.

What comes next?

Node filesystem.