How to Install Package Globally with npm in Node.js
To install a package globally in Node.js, use the command
npm install -g package-name. This makes the package available system-wide, allowing you to run its commands from any terminal.Syntax
The basic syntax to install a package globally with npm is:
npm: The Node.js package manager command.install: The command to add a package.-g: The flag that tells npm to install the package globally.package-name: The name of the package you want to install.
bash
npm install -g package-name
Example
This example shows how to install the nodemon package globally. nodemon helps automatically restart your Node.js app when files change.
bash
npm install -g nodemon
Output
+ nodemon@2.0.22
added 63 packages from 38 contributors in 5.2s
Common Pitfalls
Common mistakes when installing packages globally include:
- Not using
-gflag, which installs the package locally instead. - Permission errors on some systems, which require using
sudoon macOS/Linux. - Confusing global install with local install, which affects where the package commands are available.
Always check if you need admin rights and avoid installing packages globally unless you need command-line tools.
bash
npm install nodemon
# This installs nodemon locally, not globally
sudo npm install -g nodemon
# Use sudo on macOS/Linux if permission denied error occursQuick Reference
Summary tips for global npm installs:
- Use
npm install -g package-nameto install globally. - Use
npm list -g --depth=0to see globally installed packages. - Use
npm uninstall -g package-nameto remove a global package. - On permission errors, try
sudoon macOS/Linux or configure npm permissions properly.
Key Takeaways
Use
npm install -g package-name to install packages globally in Node.js.Global installs make package commands available anywhere in your terminal.
Use
sudo on macOS/Linux if you get permission errors during global installs.Check global packages with
npm list -g --depth=0.Avoid global installs unless you need command-line tools accessible system-wide.