AskDB
·5 min read

NPM Commands Cheat Sheet

npm is the default package manager for Node.js. This cheat sheet covers the commands you use every day.

Project Setup

npm init              # Create package.json
npm init -y           # Skip prompts, use defaults
npm install           # Install all dependencies
npm ci                # Clean install from lock file

Installing Packages

npm install lodash               # Install (save to dependencies)
npm install -D jest              # Install as devDependency
npm install lodash@4.17.21      # Specific version
npm install lodash@^4.17.0      # Compatible version
npm install -g typescript       # Install globally

Updating Packages

npm update              # Update all packages
npm update lodash       # Update specific package
npm outdated            # Check for outdated packages
npm ls                  # List installed packages
npm ls --depth=0        # Top-level only

Removing Packages

npm uninstall lodash
npm uninstall -g typescript

Running Scripts

npm run build           # Run "build" script
npm run dev             # Run "dev" script
npm test                # Run "test" script
npm start               # Run "start" script

# In package.json:
# "scripts": {
#   "dev": "next dev",
#   "build": "next build",
#   "test": "jest"
# }

npx

npx create-next-app my-app     # Run without installing
npx jest                        # Run local package binary
npx cowsay "hello"             # Run one-off commands

Version Specifiers

^4.17.0   # Compatible (4.x.x, >= 4.17.0)
~4.17.0   # Patch (4.17.x, >= 4.17.0)
4.17.0    # Exact
*         # Latest
>=4.0.0   # Range

Useful Commands

npm audit               # Security vulnerabilities
npm audit fix            # Auto-fix vulnerabilities
npm cache clean --force  # Clear cache
npm whoami               # Check logged-in user
npm publish              # Publish package
npm version patch        # Bump version

package.json Fields

{
  "name": "my-app",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": { ... },
  "dependencies": { ... },
  "devDependencies": { ... },
  "engines": { "node": ">=18" }
}