NPM - Node Package Manager
Learn how to use NPM to install, manage, and use third-party packages in your Node.js projects.
NPM (Node Package Manager) is the world's largest software registry. It lets you install and manage third-party packages in your Node.js projects.
Initializing a Project
Every Node.js project should have a package.json file:
npm init -y
This creates package.json which tracks your project's dependencies, scripts, and metadata.
Installing Packages
# Install a package (saved to dependencies)
npm install lodash
# Install as dev dependency
npm install nodemon --save-dev
# Install globally
npm install -g nodemon
Using Installed Packages
const _ = require('lodash');
const nums = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = _.chunk(nums, 3);
console.log(chunked);
// [[1, 2, 3], [4, 5, 6], [7, 8]]
const random = _.random(1, 100);
console.log(random); // Random number between 1-100
Nodemon — Auto-Restart
Nodemon is a dev tool that automatically restarts your server when files change:
# Install
npm install -g nodemon
# Use instead of node
nodemon app.js
This saves you from manually restarting the server every time you make a change.
The node_modules Folder
When you install packages, they go into node_modules/. Never commit this folder to git. Add it to .gitignore. Others can recreate it by running npm install, which reads package.json.