> ## Documentation Index
> Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 07. NPM (Node Package Manager)

> Learn how to manage dependencies and scripts with NPM.

# NPM (Node Package Manager)

One of Node.js's greatest strengths is its ecosystem. Instead of writing everything from scratch, you can leverage hundreds of thousands of open-source packages built by developers worldwide. **NPM** (Node Package Manager) is the tool that makes this possible.

## Why Package Management Matters

Imagine building a web application and needing to:

* Parse JSON data
* Make HTTP requests
* Validate user input
* Hash passwords
* Connect to a database

You *could* write all this code yourself, but it would take months. Instead, you can install battle-tested packages that solve these problems in seconds.

**The Hardware Store Analogy:** NPM is like a massive hardware store for code. You would not forge your own nails, mix your own paint, or smelt your own copper wire when building a house. You buy components that thousands of other builders have already tested. NPM works the same way--`package.json` is your shopping list, `node_modules` is your toolshed, and `package-lock.json` is the receipt that records the exact brand and model of everything you bought so your teammate gets the same parts.

### The Node.js Ecosystem

| Statistic             | Value       |
| --------------------- | ----------- |
| Total packages on NPM | 2+ million  |
| Weekly downloads      | 30+ billion |
| Active developers     | 17+ million |

This massive ecosystem means there's likely a package for almost any problem you're trying to solve.

## How NPM Works

NPM serves three main purposes:

1. **Registry**: A database of open-source packages anyone can publish to or download from
2. **CLI Tool**: A command-line tool (installed with Node.js) to install and manage packages
3. **Website**: [npmjs.com](https://npmjs.com) for discovering and learning about packages

<Tip>
  NPM comes bundled with Node.js—if you have Node installed, you already have NPM. Check with `npm --version`.
</Tip>

## package.json

The `package.json` file is the manifest for your project. It keeps track of dependencies, scripts, version, and other metadata.

To create one, run:

```bash theme={null}
npm init
# OR skip questions
npm init -y
```

## Installing Packages

### Local Installation

Installs the package in the `node_modules` folder of your current project.

```bash theme={null}
npm install lodash
```

This adds `lodash` to the `dependencies` list in `package.json`.

### Dev Dependencies

Packages only needed for development (e.g., testing tools, linters).

```bash theme={null}
npm install nodemon --save-dev
# OR
npm i -D nodemon
```

### Global Installation

Installs the package globally on your system (usually for CLI tools).

```bash theme={null}
npm install -g nodemon
```

## Using Packages

Once installed, you can require them in your code.

```javascript theme={null}
const _ = require('lodash');

const numbers = [1, 2, 3, 4, 5];
const reversed = _.reverse(numbers);
console.log(reversed);
```

## NPM Scripts

You can define custom scripts in `package.json`.

```json theme={null}
"scripts": {
  "start": "node app.js",
  "dev": "nodemon app.js",
  "test": "echo \"Error: no test specified\" && exit 1"
}
```

Run them using:

```bash theme={null}
npm run dev
npm start # Special shortcut, doesn't need 'run'
```

## Semantic Versioning (SemVer)

Versions are typically `Major.Minor.Patch` (e.g., `1.2.3`).

* **^1.2.3**: Updates to latest minor/patch version (e.g., 1.3.0, 1.2.4) but not 2.0.0. This is the default when you `npm install`.
* **\~1.2.3**: Updates to latest patch version (e.g., 1.2.4) but not 1.3.0. More conservative.
* **1.2.3**: Exact version. Most conservative--you get exactly this version, nothing else.

<Warning>
  **The caret (^) trap:** Because `^` is the default, `npm install express` writes `"express": "^4.18.2"` in your package.json. This means next time someone runs `npm install`, they might get 4.19.0 or 4.21.3--a different version than yours. This is why `package-lock.json` exists: it pins the exact resolved versions. If you delete `package-lock.json` and reinstall, you may get different dependency versions that introduce subtle bugs. This is also why you should use `npm ci` (not `npm install`) in CI/CD pipelines--it installs exactly what the lockfile specifies and fails if there is a mismatch.
</Warning>

## Summary

* **NPM** is the package manager for Node.js
* **package.json** tracks dependencies and scripts
* Use `npm install <package>` to add dependencies
* Use `npm install -D <package>` for dev dependencies
* **node\_modules** folder contains installed packages (never commit to Git--add it to `.gitignore`)

## package-lock.json

The `package-lock.json` file locks exact versions of all dependencies:

```json theme={null}
{
  "name": "my-app",
  "lockfileVersion": 3,
  "packages": {
    "node_modules/lodash": {
      "version": "4.17.21",
      "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
      "integrity": "sha512-v2kDEe57lecT..."
    }
  }
}
```

<Warning>
  Always commit `package-lock.json` to version control! It ensures consistent installs across all environments.
</Warning>

## Essential NPM Commands

```bash theme={null}
# Install all dependencies from package.json
npm install
npm i  # shorthand

# Install specific version
npm install express@4.18.2

# Install from GitHub
npm install github:user/repo

# Update packages
npm update
npm update lodash  # specific package

# Check for outdated packages
npm outdated

# Audit for security vulnerabilities
npm audit
npm audit fix  # Auto-fix vulnerabilities

# List installed packages
npm list
npm list --depth=0  # Top-level only

# View package info
npm view express
npm view express versions  # All available versions

# Search for packages
npm search keyword

# Uninstall a package
npm uninstall lodash
npm rm lodash  # shorthand

# Clean cache
npm cache clean --force

# Initialize with defaults
npm init -y
```

## NPX - Execute Packages

`npx` runs packages without installing globally:

```bash theme={null}
# Run create-react-app without installing
npx create-react-app my-app

# Run a specific version
npx node@16 --version

# Run local binaries
npx eslint .
npx jest
```

## Workspaces (Monorepos)

NPM 7+ supports workspaces for managing multiple packages:

```json theme={null}
// root package.json
{
  "name": "my-monorepo",
  "workspaces": [
    "packages/*"
  ]
}
```

```bash theme={null}
# Install dependencies for all workspaces
npm install

# Run command in specific workspace
npm run build -w packages/api

# Run command in all workspaces
npm run test --workspaces
```

## Creating Your Own Package

```bash theme={null}
# 1. Create package structure
mkdir my-package && cd my-package
npm init

# 2. Add your code
# index.js

# 3. Login to NPM
npm login

# 4. Publish (name must be unique)
npm publish

# 5. Publish scoped package
npm publish --access public  # for @username/package
```

## Popular Packages You Should Know

| Package          | Purpose                 | Weekly Downloads |
| ---------------- | ----------------------- | ---------------- |
| **express**      | Web framework           | 30M+             |
| **lodash**       | Utility functions       | 50M+             |
| **axios**        | HTTP client             | 45M+             |
| **dotenv**       | Environment variables   | 30M+             |
| **jsonwebtoken** | JWT authentication      | 15M+             |
| **bcrypt**       | Password hashing        | 5M+              |
| **mongoose**     | MongoDB ODM             | 3M+              |
| **prisma**       | Database ORM            | 2M+              |
| **jest**         | Testing                 | 25M+             |
| **nodemon**      | Auto-restart dev server | 10M+             |
| **helmet**       | Security headers        | 1M+              |
| **cors**         | CORS middleware         | 8M+              |
