Skip to main content
Node.js Basics
CHAPTER 11 Beginner

Understanding NPM

Updated: May 13, 2026
15 min read

# Understanding NPM

Welcome to Chapter 11! Up to this point, we have only used modules built directly into Node.js (fs, path, os, http). But what if you want to connect to a MongoDB database? What if you want to generate random user data or encrypt passwords? Writing that complex code from scratch would take months.

Enter NPM (Node Package Manager). NPM gives you access to over a million free, open-source libraries written by other developers. In this chapter, we will learn how to tap into this incredible resource.

---

1. Introduction

NPM consists of three parts:

  1. 1. The Website (npmjs.com): Where you can search for packages (libraries).
  1. 2. The Registry: A massive global database where all the code is stored.
  1. 3. The CLI (Command Line Interface): The tool installed on your computer alongside Node.js that allows you to download and publish packages.

A Package is simply a folder containing JavaScript files, written by someone else, that you download into your project to solve a specific problem.

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Understand the purpose of NPM.
  • Initialize a new Node.js project using npm init.
  • Search for and install local packages using npm install.
  • Require and use third-party packages in your code.
  • Understand the difference between local and global packages.

---

3. Beginner-Friendly Explanations

npm init

Before you can install packages, your project needs a way to keep track of *which* packages you installed. You run npm init in your terminal to initialize a project. It asks you a few questions and generates a special file called package.json.

npm install <package-name>

When you run this command, NPM connects to the internet, downloads the requested package, and places it inside a newly created folder named node_modules in your project directory.

Core Modules vs Local Modules vs NPM Packages

  • Core (require('fs')): Built into Node.js. No installation needed.
  • Local (require('./math')): Files *you* wrote. Requires ./ path.
  • NPM (require('axios')): Downloaded from the internet. No ./ path needed. Node automatically looks inside the node_modules folder to find it.

---

4. Syntax Explanation

Let's look at terminal commands used to manage NPM.

```bash id="ch11-bash-1" # 1. Initialize a project (creates package.json) npm init -y

# 2. Install a package named 'lodash' npm install lodash

# 3. Uninstall a package npm uninstall lodash

1234567891011121314151617181920212223
*Note: The `-y` flag stands for "yes". It skips the questionnaire and creates a default `package.json` file instantly.*

---

## 5. Real-world Examples

**Why use NPM?**
Imagine you are building a social media app. You need to format dates ("Posted 2 hours ago"). You *could* write a massive mathematical function handling leap years, timezones, and months... OR you could just run `npm install date-fns`, require it, and use their perfect, bug-free `.formatDistanceToNow()` function. 

NPM allows developers to focus on their unique business logic rather than reinventing the wheel.

---

## 6. Multiple Code Examples

### Example 1: Installing and using `chalk`
The terminal is usually boring white text. The `chalk` package allows us to print colorful text.

*In the terminal:*
`npm init -y`
`npm install chalk@4` *(Note: We use version 4 here because version 5 requires ES Modules. We'll stick to CommonJS for now).*

*In `app.js`:*

javascript id="ch11-code-1" // Notice we don't use './'. Node looks in node_modules! const chalk = require('chalk');

console.log(chalk.blue('Hello world!')); console.log(chalk.green.bold('SUCCESS! Database connected.')); console.log(chalk.red.inverse('ERROR: Something went wrong.'));

1234567
### Example 2: Installing `uuid`
Often, databases need unique IDs. The `uuid` package generates cryptographically strong random IDs.

*In the terminal:*
`npm install uuid`

*In `app.js`:*

javascript id="ch11-code-2" // Destructure the v4 function from the uuid package const { v4: uuidv4 } = require('uuid');

const newUser = { id: uuidv4(), // Generates something like: '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' name: "John Doe" };

console.log(newUser);

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
### Example 3: Global Packages
Some packages are tools you run from the terminal anywhere on your computer, rather than code you `require()` inside a project. To install a global package, use the `-g` flag.

**Nodemon** is a famous global package. It watches your files, and whenever you hit "Save", it automatically restarts your server!

*In the terminal:*
`npm install -g nodemon`

Now, instead of running `node server.js`, you can run `nodemon server.js`. Try it!

---

## 7. Output Explanations

When you run `npm install`, you will notice a few things appear in your folder:
1. **`node_modules/` folder:** This is where the actual code of the downloaded package lives. (Do NOT edit files in here!)
2. **`package-lock.json`:** A highly detailed blueprint that locks in the exact versions of every package installed to ensure consistency across different computers.

---

## 8. Common Mistakes

1. **Forgetting `npm init`:** If you try to install packages without initializing your project first, NPM will still install them, but it won't track them in a `package.json`, which will cause major issues later when you deploy your app.
2. **Pushing `node_modules` to GitHub:** The `node_modules` folder can be hundreds of megabytes in size. You should NEVER upload it to GitHub or share it with friends. You only share the `package.json` file. (We fix this using a `.gitignore` file).
3. **Misspelling package names:** If you type `npm install reactt`, NPM might install a malicious package created by a hacker hoping you would misspell the real name. Always verify package names on `npmjs.com`!

---

## 9. Best Practices

- **Always check Weekly Downloads:** On `npmjs.com`, look at how many times a package is downloaded per week. If it has 5 million downloads, it's safe. If it has 12 downloads, do not trust it in your production app!
- **Use `nodemon` for development:** It will save you hours of time not having to manually stop and start the server every time you make a change.

---

## 10. Exercises

1. Create a brand new folder on your computer. Open it in VS Code and open the terminal.
2. Run `npm init -y`.
3. Go to `npmjs.com` and search for `validator`. Install it using `npm install validator`.
4. Create an `index.js` file, require the `validator` package, and use `validator.isEmail('test@test.com')` to check if an email is valid. Log the result.

---

## 11. Mini Project: Install utility packages

**Objective:** Build a simple app that uses multiple NPM packages to format a random user profile.

**Step 1:** Initialize and install

bash mkdir npm-project cd npm-project npm init -y npm install casual chalk@4

123
*(The `casual` package generates fake data like names, addresses, and emails).*

**Step 2:** Code (`profile.js`)

javascript id="ch11-mini-project" // profile.js const casual = require('casual'); const chalk = require('chalk');

// Generate a fake user const user = { name: casual.full_name, email: casual.email, country: casual.country, password: casual.password };

// Print beautifully to terminal console.log(chalk.bgBlue.white.bold("\n NEW USER REGISTERED \n")); console.log(chalk.green("Name: ") + user.name); console.log(chalk.yellow("Email: ") + user.email); console.log(chalk.cyan("Location: ") + user.country); console.log(chalk.red("Temp Password: ") + user.password); console.log("\n=========================\n"); ``

Run it: node profile.js

---

12. Coding Challenges

Challenge 1: Install the qrcode package. Write a script that turns a string (like a URL) into a QR code and prints it directly in the terminal using qrcode.toString(). Check the NPM documentation for syntax!

Challenge 2: Install the date-fns package. Use it to calculate exactly how many days have passed since the year 2000.

---

13. MCQs with Answers

Q1: What command initializes a new Node.js project and creates a package.json? A) npm start B) node init C) npm init D) npm create Answer: C

Q2: Where does NPM physically store the code of the packages you install? A) In the package.json file. B) In a hidden .npm folder. C) In the node_modules folder. D) In the npm_packages folder. Answer: C

Q3: How do you require a package you installed via NPM? A) require('./packagename') B) require('packagename') C) import('packagename') D) require('/node_modules/packagename') Answer: B

Q4: What flag do you use to install a package globally on your computer? A) -a B) --all C) -g D) -global Answer: C

---

14. Interview Questions

  1. 1. What is the difference between local and global NPM packages?
*Answer:* Local packages are installed within a specific project folder (inside
node_modules) and are accessed via require() in the code. Global packages are installed on the operating system itself and are usually CLI tools executed directly in the terminal (like nodemon).
  1. 2. Why do we need a package.json file?
*Answer:* It acts as the manifest for the project. It tracks metadata (name, author) and, most importantly, keeps a list of all dependencies (NPM packages) required for the app to run.
  1. 3. Should you commit node_modules to Git?
*Answer:* No. It is too large. Instead, you commit package.json. Another developer can clone your repository and simply run npm install to regenerate the node_modules folder based on the dependencies listed in package.json.

---

15. FAQs

Q: Are NPM packages safe to use? A: Mostly, yes. But since anyone can upload a package, you should stick to highly downloaded packages with active GitHub repositories.

Q: Do I have to pay for NPM? A: No, accessing and downloading public packages is 100% free.

---

16. Summary

  • NPM is the largest software registry in the world.
  • Use npm init -y to start a project and generate a package.json.
  • Use npm install <package> to download third-party code.
  • Downloaded code lives inside the node_modules folder.
  • Import packages simply by passing their name into require('name').

---

17. Next Chapter Recommendation

We mentioned package.json` a lot, but we haven't actually looked inside it! In Chapter 12: Node.js Package.json and Dependencies, we will dissect this file, learn the difference between dependencies and devDependencies, and learn how to write custom NPM scripts to automate our workflow.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·