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
- Initialize a project with
npm initto create a package.json file. - Install a production dependency with
npm install express. - Install a development dependency with
npm install --save-dev nodemon. - Install all dependencies from an existing project with
npm install. - Run scripts defined in the
scriptssection of package.json withnpm run devornpm start.
Tips
- Use
npm ciin CI/CD pipelines for faster, reproducible installs that respect the exact versions in package-lock.json. - Regularly run
npm auditto check for known vulnerabilities in your dependencies. - Use
npm outdatedto 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 installagain.