Skip to main content
Node.js Package Manager:

npm cheat sheet

Summary

This npm cheat sheet documents the most frequently used commands for Node.js package management. It includes package installation, configuration, script execution, and publishing workflows.

Introduction #

npm stands for Node Package Manager. It is the default package manager for the Node.js JavaScript runtime. You use it to install, manage, and publish packages written in JavaScript.

Command overview #

Installation & version management #

CommandExplanation
node -vDisplays installed Node.js version
npm -vDisplays installed npm version
npm install -g npmUpdates npm to latest version

Project initialization #

CommandExplanation
npm initInteractive package.json creation
npm init -yDefault package.json creation
npm init -w ./packages/...Create workspace (monorepo support)

Package installation #

CommandExplanation
npm i <package>Install package (shorthand)
npm i <package> -DInstall as devDependency
npm i <package>@<version>Install specific version
npm i -g <package>Global installation
npm iInstall all dependencies
npm ciClean install (uses lockfile)
npm i --ignore-scriptsInstall without running package scripts
npm i -w <workspace-name> <package>Install in specific workspace

Package management #

CommandExplanation
npm rm <package>Remove package (shorthand)
npm up <package>Update package (shorthand)
npm updateUpdate all packages
npm upgrade-interactiveInteractive update
npm outdatedList outdated packages
npm dedupeReduce duplication in node_modules

Package information #

CommandExplanation
npm listShow installed packages
npm list --depth=0Show only top-level packages
npm list -gShow globally installed packages
npm view <package>Show package metadata
npm info <package>Detailed package info
npm repo <package>Open package repository
npm docs <package>Open package documentation
npm search <query>Search registry
npm fundShow funding info for dependencies
npm licenses listList licenses of dependencies

Scripts & execution #

CommandExplanation
npm run <script>Run custom script
npm startRun start script
npm testRun test script
npm exec <command>Run command with local binaries
npx <package>Run package binary
npx -p <package> <cmd>Run command after installing package

Security #

CommandExplanation
npm auditScan for vulnerabilities
npm audit fixFix vulnerabilities
npm doctorCheck npm environment
npm pingTest registry connectivity

Publishing #

CommandExplanation
npm loginAuthenticate to registry
npm publishPublish package
npm publish --access publicPublish scoped package publicly
npm publish --tag betaPublish with custom tag
npm unpublishRemove published package
npm dist-tag add <pkg>@<ver> <tag>Add distribution tag
npm dist-tag ls <pkg>List distribution tags
npm token createCreate auth token
npm token listList auth tokens
npm org ls <org>List organization members

Configuration #

CommandExplanation
npm config get <key>Get config value
npm config set <key> <value>Set config value
npm config delete <key>Delete config value
npm config listList all configs
npm config editEdit config file
npm prefixShow local prefix (installation directory)
npm root -gShow global node_modules location

Cache management #

CommandExplanation
npm cache verifyVerify cache integrity
npm cache clean --forceClear cache (use with caution)

Version management #

CommandExplanation
npm version patchBump patch version (0.0.x)
npm version minorBump minor version (0.x.0)
npm version majorBump major version (x.0.0)

Common Workflows #

New Project Setup #

mkdir my-project
cd my-project
npm init -y
npm install express
npm install jest --save-dev

Update Dependencies #

npm outdated
npm update
# Or for interactive updates:
npm upgrade-interactive

Publish a Package #

npm login
npm version patch
npm publish

Security Check #

npm audit
npm audit fix
npm install --audit

Package.json #

Example File #

{
  "name": "my-package",
  "version": "1.0.0",
  "description": "A sample package",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "jest",
    "prepublishOnly": "npm test",
    "prepare": "husky install"
  },
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "jest": "^29.5.0"
  },
  "engines": {
    "node": ">=18.0.0",
    "npm": ">=9.0.0"
  },
  "files": ["dist/"],
  "bin": {
    "my-cli": "./cli.js"
  },
  "keywords": ["example", "demo"],
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/user/repo.git"
  }
}

Key fields reference #

FieldTypeRequiredDescription
nameStringYesPackage name (lowercase, no spaces, may include hyphens and underscores)
versionStringYesFollows Semantic Versioning (SemVer) format MAJOR.MINOR.PATCH
descriptionStringNoBrief package description (shown in npm search)
mainStringNoEntry point file (e.g., index.js) when required
scriptsObjectNoKey-value pairs of runnable npm scripts
dependenciesObjectNoProduction dependencies (installed with npm install --save)
devDependenciesObjectNoDevelopment dependencies (installed with npm install --save-dev)
peerDependenciesObjectNoPackages required by but not automatically installed with your package
optionalDependenciesObjectNoOptional packages that won’t fail install if unavailable
enginesObjectNoSpecifies Node/npm version requirements
filesArrayNoWhitelist of files to include in published package
binObject/StringNoCLI commands your package provides
keywordsArrayNoHelps discoverability in npm search
licenseStringNoSPDX license identifier (e.g., “MIT”, “ISC”)
repositoryObjectNoSource code location (typically Git)
homepageStringNoProject website URL
bugsObject/StringNoIssue tracker URL
authorObject/StringNoPackage creator info
contributorsArrayNoAdditional contributors
privateBooleanNoPrevents accidental publishing when true
workspacesArrayNoEnables monorepo support (Yarn/npm workspaces)
typeStringNoModule system ("module" for ESM, "commonjs" for CJS)
exportsObjectNoModern alternative to main with advanced conditional exports

Common script hooks #

ScriptTriggerCommon Use
prepublishBefore package is packed and publishedDeprecated in favor of prepare
prepareAfter install (including git clones)Build steps, husky setup
prepublishOnlyBefore npm publishFinal tests before publishing
preinstallBefore package installEnvironment checks
postinstallAfter package installCompilation tasks
prestartBefore npm startSetup tasks
poststartAfter npm startCleanup tasks
pretestBefore npm testTest setup
posttestAfter npm testTest coverage

Version range syntax #

SyntaxExampleMeaning
Exact version4.18.2Only this exact version
Caret (^)^4.18.2Any version compatible with 4.x.x (>=4.18.2 <5.0.0)
Tilde (~)~4.18.2Any patch version (>=4.18.2 <4.19.0)
Greater/less>=4.0.0 <5.0.0Version range
Wildcard (x)4.18.xAny patch version in 4.18 series
latestlatestThe newest available version

Best Practices #

  1. Use exact versions in production:
    npm config set save-exact true
    
  2. Enable 2FA for publishing:
    npm profile enable-2fa
    
  3. Verify packages before installing:
    npm view <package> dependencies
    npm view <package> dist.integrity
    
  4. Use workspaces for monorepos:
    {
      "workspaces": ["packages/*"]
    }
    
  5. Clean install in CI:
    npm ci
    
  6. Include only necessary files:
    {
      "files": ["dist/", "lib/"]
    }
    

Troubleshooting #

Common Issues #

  • EACCES errors: Use npm config set prefix ~/.npm-global
  • Peer dependency conflicts: Use npm install --legacy-peer-deps
  • Missing scripts: Check package.json scripts section
  • Cache problems: Run npm cache verify

Diagnostic Commands #

npm doctor
npm ls <problem-package>
npm view <package> versions

FAQ's #

Most common questions and brief, easy-to-understand answers on the topic:

What does npm stand for?

It stands for Node Package Manager, and it is the default package manager for the Node.js runtime environment.

How do you update a package using npm?

You run npm update <package-name> or use npm outdated to check outdated packages first.

Where is the global node_modules folder?

Run npm root -g to print the path to the globally installed node_modules directory.

How can you list installed packages?

Run npm list for local and npm list -g for global packages. Add --depth=0 to skip nested dependencies.

What file defines npm project dependencies?

The package.json file defines dependencies, scripts, and metadata for an npm project.

Further readings #

Sources and recommended, further resources on the topic:

Author

Jonas Jared Jacek • J15k

Jonas Jared Jacek (J15k)

Jonas works as project manager, web designer, and web developer since 2001. On top of that, he is a Linux system administrator with a broad interest in things related to programming, architecture, and design. See: https://www.j15k.com/

License

npm cheat sheet by Jonas Jared Jacek is licensed under CC BY-SA 4.0.

This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. To give credit, provide a link back to the original source, the author, and the license e.g. like this:

<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/npm-cheat-sheet">npm cheat sheet</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-SA 4.0</a>.</p>

For more information see the Ditig legal page.

All Topics

Random Quote

“Form ever follows function.”

Louis Henry Sullivan American architectThe Tall Office Building Artistically Considered, - IT quotes