How to install NodeJS packages using NPM

Highlighting different kinds of package dependencies and its scope of access

Node Package Manager—abbreviated as NPM, is an online software repository where open source Nodejs projects are published as packages. It also doubles as a command line utility that helps users interact with the online software repository. Open source refers to projects whose source code has been made available to everyone online to use and modify. The idea behind NPM is to make software development easier and avoid pointless iterative creation of already existing solutions.

NPM does not come pre-installed in any operating system so users have to install it first. However, it comes along with Nodejs. If you have Nodejs already installed in your system, you are good to go else click on the previous link to install.

After installation, you can confirm your npm version by typing the following in your command line:

npm --version
# alternatively, you can use
npm -v

To install any package using npm, open your command line tool and type the following:

# replace packageName with the intended package
npm install <packageName>
# alternatively, you can use
npm i <packageName>

Package installation can be done using any of the following form of dependencies:

  • Local dependency

  • Global dependency

If a package is installed as a local dependency, this means that it can only be used inside the current project. Example, a user creates a project folder titled blog and installs express framework inside the folder using the command below. Express can only be used inside the project and nowhere else.

# install express locally
npm install express

Globally installed packages can be used both inside the current project and other projects available in the operating system. The package gets added to the Nodejs path rendering it accessible to all projects in the operating system. Using the same example above, let's say the user now wants to create an e-commerce app but does not want to reinstall express, the command below makes express framework globally accessible.

npm install -g express
# if you are using mac, use the sudo command
sudo npm install -g express

The -g flag sets the location of the installation.

NPM as a tool and software repository has made software development easier and faster, thanks to countless software engineers who encountered problem/s at some point in their project/s and decided to make their solution public. I hope the information provided above was helpful to you. Happy coding!