NelsonLabs
Node.js Fundamentals/npm & Package Management

npm & Package Management

npm (Node Package Manager) is the world's largest software registry. It lets you install and reuse code others have written — from utility functions to complete frameworks. Understanding how it works prevents a lot of confusion.

npm commands you'll use every day
bash
# Initialise a new project (creates package.json)
npm init          # interactive setup
npm init -y       # accept all defaults

# Install packages
npm install express          # installs to node_modules, adds to dependencies
npm install --save-dev jest  # adds to devDependencies (only for development)
npm install -g nodemon       # global install (available everywhere on your system)

# Install all dependencies from package.json (e.g., after git clone)
npm install

# Run scripts defined in package.json
npm run dev
npm run build
npm test            # shorthand for npm run test
npm start           # shorthand for npm run start

# Remove a package
npm uninstall express

# Check for outdated packages
npm outdated

# Update packages
npm update
package.json — what it does
json
{
  "name": "my-api",
  "version": "1.0.0",
  "description": "A Node.js REST API",
  "main": "src/index.js",

  "scripts": {
    "start":  "node src/index.js",
    "dev":    "nodemon src/index.js",
    "test":   "jest",
    "build":  "tsc"
  },

  "dependencies": {
    "express": "^4.18.2",
    "dotenv":  "^16.0.3"
  },

  "devDependencies": {
    "nodemon": "^3.0.0",
    "jest":    "^29.0.0"
  }
}

TIP

Commit package.json and package-lock.json, ignore node_modules. Always commit package.json (what you need) and package-lock.json (the exact versions that were installed). Never commit node_modules/ — it's huge and regenerated with npm install. Add it to .gitignore.