How to Install Package Using npm in Node.js Quickly
To install a package using
npm in Node.js, run npm install package-name in your terminal inside your project folder. This downloads the package and adds it to your node_modules folder and package.json dependencies.Syntax
The basic syntax to install a package using npm is:
npm install package-name: Installs the package locally in your project.npm install -g package-name: Installs the package globally on your system.package-nameis the name of the package you want to add.
bash
npm install package-name
Example
This example shows how to install the popular express package locally in a Node.js project.
bash
npm install express
Output
+ express@4.18.2
added 50 packages from 37 contributors and audited 50 packages in 2.5s
found 0 vulnerabilities
Common Pitfalls
Common mistakes when installing packages include:
- Running
npm installoutside your project folder, so the package installs in the wrong place. - Forgetting to save the package to
package.json(usually automatic, but can be missed with old npm versions). - Trying to use a package without installing it first.
Always check you are in the correct folder and use the latest npm version.
bash
npm install express // Correct way: installs express locally npm install -g express // Global install, usually not needed for libraries // Wrong: using a package without installing const express = require('express'); // This will cause an error if express is not installed
Quick Reference
| Command | Description |
|---|---|
| npm install package-name | Install package locally in current project |
| npm install -g package-name | Install package globally on your system |
| npm uninstall package-name | Remove a package from your project |
| npm update package-name | Update a package to the latest version |
| npm install | Install all dependencies listed in package.json |
Key Takeaways
Run
npm install package-name inside your project folder to add a package.Local installs add packages to
node_modules and update package.json automatically.Use
npm install -g only for tools you want available system-wide.Always check you are in the right folder before installing packages.
Keep npm updated to avoid installation issues.