How to use the npm package manager

· Category: Node.js

Short answer

npm is the default package manager for Node.js. Use npm install <package> to add dependencies and npm run <script> to execute commands defined in package.json.

Steps

  1. Initialize a project with npm init to create a package.json file.
  2. Install a production dependency with npm install express.
  3. Install a development dependency with npm install --save-dev nodemon.
  4. Install all dependencies from an existing project with npm install.
  5. Run scripts defined in the scripts section of package.json with npm run dev or npm start.

Tips

  • Use npm ci in CI/CD pipelines for faster, reproducible installs that respect the exact versions in package-lock.json.
  • Regularly run npm audit to check for known vulnerabilities in your dependencies.
  • Use npm outdated to see which packages have newer versions available.

Common issues

  • Permission errors during global installs can often be fixed by configuring npm to use a different global directory or using a Node version manager.
  • If node_modules becomes corrupted, delete it and the package-lock.json, then run npm install again.