When you install Node.js, you get another incredibly powerful tool bundled with it for free: NPM, which stands for Node Package Manager.
NPM is the world's largest software registry. It contains over two million packages of pre-written JavaScript code that you can easily download and integrate into your own projects. Why reinvent the wheel when another developer has already written and tested the code you need?
NPM consists of three distinct parts:
To verify that you have NPM installed on your machine, run the following command in your terminal:
npm -v
By default, when you use NPM to install a package, it is installed locally. This means the package is only accessible to the specific project folder you are currently inside.
For example, if you want to create an API, you will likely need the popular web framework called express. You can download it into your project by typing:
npm install express
(Note: npm i express is a common shorthand for npm install express)
express package.node_modules.package.json file to keep a record of the installation.Once installed, you can require/import it in your files just like a core Node.js module!
// We can now use the express package!
const express = require('express');
const app = express();
console.log("Express was successfully loaded from node_modules!");
Some packages are not meant to be imported into your code. Instead, they are command-line tools that you want to be able to run from anywhere on your computer, regardless of the folder you are in.
To install a package globally, you add the -g flag to your install command.
For example, nodemon is a fantastic tool that automatically restarts your Node server whenever you save a file:
npm install -g nodemon
Now, instead of running node app.js, you can run nodemon app.js in any directory on your computer!
node_modules FolderIf you open your project folder after running an npm install, you will see a node_modules directory. This folder contains all the source code for the packages you downloaded.
Crucial Rule: NEVER commit the node_modules folder to GitHub or send it to a friend! It can easily become hundreds of megabytes in size. Instead, developers share the package.json file, and anyone who downloads the project simply runs npm install to re-download all the missing packages automatically.
What is the correct command to install an NPM package globally on your machine?