About npm
npm (Node Package Manager) is the default package manager for Node.js and the world's largest software registry. With over 2 million packages, npm is essential not just for JavaScript developers, but for system administrators who need to install and manage command-line tools, utilities, and automation scripts.
Why Sysadmins Need npm:
- CLI Tools: Many modern utilities distributed via npm (serverless, aws-cdk, pm2)
- Build Tools: Webpack, Babel, and other essential tooling
- Automation: Task runners, deployment scripts, monitoring tools
- Universal Format: Cross-platform package distribution
- Version Control: Reproducible environments with package.json
Key Concepts:
- package.json: Project manifest - lists dependencies and scripts
- node_modules: Directory where packages are installed
- package-lock.json: Locks exact versions for reproducibility
- Global vs Local: System-wide tools vs project-specific packages
- Semantic Versioning: Major.Minor.Patch (1.2.3)
- Scripts: Custom commands defined in package.json
- Dependencies: Production code requirements
- DevDependencies: Development/build tools only
Common Use Cases:
- Installing command-line tools globally (pm2, serverless, newman)
- Managing project dependencies for Node.js applications
- Running build scripts and automation tasks
- Auditing and fixing security vulnerabilities
- Publishing internal packages to private registries
- Creating reproducible development environments
| Command | Description |
|---|---|
npm install [package] |
Install package locally |
npm install -g [package] |
Install package globally (system-wide) |
npm uninstall [package] |
Remove package |
npm update [package] |
Update package to latest compatible version |
npm list |
List installed packages |
npm search [term] |
Search npm registry |
npm init |
Create new package.json |
npm run [script] |
Execute script from package.json |
npm audit |
Check for security vulnerabilities |
npm publish |
Publish package to registry |
| Option | Description |
|---|---|
-g, --global |
Install globally (system-wide) |
--save, -S |
Add to dependencies (default) |
--save-dev, -D |
Add to devDependencies |
--save-exact, -E |
Pin exact version (no ^ or ~) |
--production |
Skip devDependencies |
--dry-run |
Simulate without making changes |
--json |
Output in JSON format |
--depth=N |
Limit dependency tree depth |
Example 1Installing Packages Locally and Globally
Understanding local vs global installation:
Explanation:
npm init -y: Create package.json with defaults- Local install: Adds to
./node_modules/ - Local installs added to package.json automatically
-g: Install globally to system PATH- Global installs accessible as commands anywhere
- Use local for libraries, global for CLI tools
sudo npm install -g by configuring npm to use user directory: npm config set prefix ~/.npm-global then add ~/.npm-global/bin to PATH. Safer and avoids permission issues.
Example 2Managing Dependencies in package.json
Understanding dependencies and version specifications:
Explanation:
dependencies: Required for productiondevDependencies: Only for development/testing^4.18.2: Caret - allows minor/patch updates (4.x.x)~4.18.2: Tilde - allows only patch updates (4.18.x)18.2.0: Exact version - no updates--save-exact: Pin versions for reproducibility
--save-exact for production applications to ensure reproducible builds. For libraries, use caret (^) to allow compatible updates. Check package-lock.json into version control to lock all transitive dependencies.
Example 3Listing and Searching Packages
Find installed packages and search for new ones:
Explanation:
npm list: Show dependency tree--depth=0: Only show top-level packagesnpm view: Show package information from registrynpm search: Find packages by keyword- Use
npm list -gto audit global tools - Check npmjs.com for detailed package docs
npm outdated. Shows current, wanted, and latest versions. Use npm update to update within semver ranges, or npm install package@latest for major updates.
Example 4Using npm Scripts for Automation
Define custom scripts in package.json:
Explanation:
npm run [script]: Execute custom script- Scripts can call other npm scripts
&&: Chain commands (runs if previous succeeds)pre*andpost*: Auto-run hooksstart,test: Special - don't need "run"- Scripts see node_modules/.bin in PATH
dev (development server), build (production build), test (run tests), lint (code quality), deploy (deployment). Keep CI/CD simple: npm test && npm run build.
Example 5Security Auditing and Vulnerability Fixes
Check for and fix security vulnerabilities:
Explanation:
npm audit: Scan dependencies for known vulnerabilitiesnpm audit fix: Auto-update to secure versions--force: Install breaking changes if needed--audit-level: Set severity threshold- Reports link to CVE details and advisories
- Essential for compliance and security
npm audit regularly, especially before deployments. Add to CI/CD: npm audit --audit-level=moderate to fail builds with vulnerabilities. Review audit fix --force changes carefully in dev before production. Subscribe to security advisories for critical packages.
Example 6Working with package-lock.json
Understanding and managing the lock file:
Explanation:
- package-lock.json: Locks exact versions of ALL dependencies
- Includes transitive dependencies (dependencies of dependencies)
npm ci: Clean install from lock file (faster, reproducible)npm install: Updates lock file if needed- Lock file ensures identical installs across team/environments
- ALWAYS commit package-lock.json to git
npm ci in automated builds, not npm install. It's faster, stricter, and won't modify package-lock.json. Fails if package.json and lock file are out of sync. Perfect for production deployments and testing.
Example 7Installing Global CLI Tools
Manage system-wide command-line utilities:
Explanation:
pm2: Production process managernodemon: Auto-restart on file changes (development)http-server: Simple static file servernpm-check-updates: Find outdated dependenciestldr: Simplified man pages- Global tools accessible from any directory
pm2 (process management), npm-check-updates (dependency updates), serve (quick file server), localtunnel (expose local server), npx (run packages without installing).
Example 8Using npx to Run Packages Without Installing
Execute packages without global installation:
Explanation:
npx: Execute packages without installing globally- Downloads package temporarily to cache
- Perfect for one-off commands or testing
- Always runs latest version (unless specified)
- Cleaner than installing global packages
- Comes bundled with npm 5.2+
npx over global installs for tools you don't use daily. Examples: npx create-react-app, npx eslint, npx prettier. Ensures latest version and avoids global namespace pollution. Great for CI/CD and scripts.
Example 9Configuring npm and Registry Settings
Customize npm behavior and use private registries:
Explanation:
- Config stored in
~/.npmrc(user) and/usr/local/etc/npmrc(global) init-*: Defaults fornpm initprefix: Where global packages installregistry: Package registry URL- Scoped packages can use different registries
- Authentication via tokens, not passwords
npm config set @company:registry https://npm.company.com/. Then npm install @company/package uses private registry automatically.
Example 10Complete Project Setup and Deployment
Real-world example: Initialize, develop, and deploy Node.js app:
Explanation:
- Complete project lifecycle from init to deployment
npm pkg set: Modern way to update package.json- Separate dev and production dependencies
- Scripts for all development tasks
npm ci --production: Production deployment- PM2 for production process management
npm ci not npm install, (2) Set NODE_ENV=production, (3) Install only production deps (--production), (4) Run security audit, (5) Use process manager (PM2, systemd), (6) Enable monitoring and logging, (7) Configure reverse proxy (nginx).
Using sudo npm install -g causes permission problems.
Solution: Configure npm to install globally to user directory: npm config set prefix ~/.npm-global, add export PATH=~/.npm-global/bin:$PATH to ~/.bashrc. Or use nvm which handles this automatically.
Omitting lock file from git causes inconsistent installs across team.
Solution: ALWAYS commit package-lock.json to version control. It ensures everyone gets identical dependencies. Only exception: publishing libraries (not applications) where you want consumers to get latest compatible versions.
npm install can update lock file, causing build inconsistencies.
Solution: Use npm ci in automated builds. It's faster, stricter, and won't modify package-lock.json. Fails if files are out of sync, catching issues early.
Deploying applications with known vulnerabilities.
Solution: Run npm audit before deployments. Add to CI/CD: npm audit --audit-level=moderate. Set up automated scanning (Snyk, Dependabot). Subscribe to security advisories for critical packages.
Build tools and test frameworks in production dependencies.
Solution: Use --save-dev for development tools: npm install --save-dev jest eslint webpack. Production deploys skip devDependencies with --production flag, reducing size and attack surface.
node_modules can grow to hundreds of MB or GB.
Solution: Don't commit node_modules to git (add to .gitignore). Use npm prune to remove extraneous packages. Consider pnpm for space efficiency. For Docker: use multi-stage builds and .dockerignore.
Project-level config ensures team uses same settings:
Commit .npmrc to git. Team gets consistent behavior automatically.
Several techniques to faster installations:
Consider npm caching in CI/CD environments.
Understand version constraints:
Use ^ for libraries, exact for critical dependencies, ~= for security patches only.
Find and remove packages you're not using:
Keeps package.json clean and reduces security surface area.
Use .env files and separate configs:
Never commit .env to git. Use .env.example as template.
Keep dependencies current without manual work:
Or use Dependabot/Renovate for automated PRs.
| Task | Command |
|---|---|
| Initialize project | npm init -y |
| Install package locally | npm install package |
| Install package globally | npm install -g package |
| Install dev dependency | npm install --save-dev package |
| Install from package.json | npm install |
| Clean install (CI/CD) | npm ci |
| Update packages | npm update |
| Uninstall package | npm uninstall package |
| List installed packages | npm list --depth=0 |
| Check for outdated | npm outdated |
| Security audit | npm audit |
| Fix vulnerabilities | npm audit fix |
| Run script | npm run script-name |
| Run without installing | npx package |
| View package info | npm view package |