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
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
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:- Registry: A database of open-source packages anyone can publish to or download from
- CLI Tool: A command-line tool (installed with Node.js) to install and manage packages
- Website: npmjs.com for discovering and learning about packages
package.json
Thepackage.json file is the manifest for your project. It keeps track of dependencies, scripts, version, and other metadata.
To create one, run:
Installing Packages
Local Installation
Installs the package in thenode_modules folder of your current project.
lodash to the dependencies list in package.json.
Dev Dependencies
Packages only needed for development (e.g., testing tools, linters).Global Installation
Installs the package globally on your system (usually for CLI tools).Using Packages
Once installed, you can require them in your code.NPM Scripts
You can define custom scripts inpackage.json.
Semantic Versioning (SemVer)
Versions are typicallyMajor.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.
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
Thepackage-lock.json file locks exact versions of all dependencies:
Essential NPM Commands
NPX - Execute Packages
npx runs packages without installing globally: