npm (Node Package Manager) is the default package manager for Node.js and the world's largest software registry. It provides two main functionalities:
In essence, npm helps you manage external libraries and tools your JavaScript projects need, making it easy to include complex functionalities without writing everything from scratch.
npm is distributed with Node.js. When you install Node.js, npm is installed automatically.
Open your terminal or command prompt and run the following commands:
node -v
npm -v
You should see the installed versions of Node.js and npm respectively.
# Example Output:
v20.14.0 # Node.js version
10.7.0 # npm version
Before you can use npm to manage dependencies for your project, you need to initialize it. This creates a `package.json` file, which is the heart of any npm project.
Navigate to your project's root directory in the terminal:
mkdir my-npm-project
cd my-npm-project
npm init
npm will then ask you a series of questions (package name, version, description, entry point, test command, git repository, keywords, author, license). You can press Enter to accept the default values for most of these.
# After running npm init and accepting defaults, your package.json might look like this:
{
"name": "my-npm-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
To accept all default values without being prompted, use the `-y` or `--yes` flag:
npm init -y
This is useful for quickly setting up new projects or for scripting.
This is the most common npm command, used to add external libraries to your project.
Installs a package into your project's `node_modules` folder and adds it as a dependency in `package.json`.
npm install <package-name>
Example: Installing Express.js (a web framework)
npm install express
This command does two things:
# package.json after installing express
{
"name": "my-npm-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2" // This line is added
}
}
Installs a package needed only during development (e.g., testing frameworks, build tools, linters). These are not deployed with your production code.
npm install <package-name> --save-dev
# Or shorthand:
npm install <package-name> -D
Example: Installing Jest (a testing framework)
npm install jest --save-dev
# package.json after installing jest as a dev dependency
{
// ...
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": { // This new section is added
"jest": "^29.5.0"
}
}
You can install several packages at once:
npm install express dotenv mongoose
npm install webpack webpack-cli -D
If you've cloned a project or a `node_modules` folder was deleted, you can install all dependencies listed in `package.json`:
npm install
This command reads `package.json` and `package-lock.json` and installs all necessary packages.
These two files are crucial for managing your project's dependencies.
This file defines your project's metadata (name, version, description, author, license) and lists its direct dependencies.
# Example package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "A simple Node.js application",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "jest",
"dev": "nodemon index.js"
},
"dependencies": {
"express": "^4.18.2",
"dotenv": "^16.0.3"
},
"devDependencies": {
"jest": "^29.5.0",
"nodemon": "^2.0.22"
}
}
Dependency Versioning:
This file is automatically generated and updated by npm whenever you modify your `node_modules` tree (e.g., `npm install`, `npm update`). It records the exact versions of *all* installed packages and their dependencies (even nested ones), along with their integrity hashes.
Purpose: Ensures that running `npm install` on any machine (or by any developer) will result in the exact same `node_modules` tree, providing consistent builds and preventing "works on my machine" issues.
# Example snippet from package-lock.json (much larger than package.json)
{
"name": "my-npm-project",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "my-npm-project",
"version": "1.0.0",
"devDependencies": {
"jest": "^29.5.0"
},
"dependencies": {
"express": "^4.18.2"
}
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-py/yzLCYmY6F/UtyUzN/P3W+jSykx+Jt0pQ7y1/NfB3+yI+Ew/uF9bFvG8GjA==",
"dependencies": {
"mime-types": "~2.1.24",
"negotiator": "0.6.3"
}
},
// ... many more entries for nested dependencies
}
}
Removes a package from your `node_modules` folder and from `package.json`.
npm uninstall <package-name>
# Or shorthand:
npm un <package-name>
Example:
npm uninstall express
npm uninstall <package-name> --save-dev
# Or shorthand:
npm un <package-name> -D
Example:
npm uninstall jest -D
Updates packages to their latest compatible versions according to the version ranges specified in `package.json`.
npm update
This command will check the npm registry for newer versions of all packages (and their dependencies) that satisfy the version ranges in your `package.json` and `package-lock.json`, and then update them in `node_modules` and update `package-lock.json` accordingly.
npm update <package-name>
`npm update` will NOT update to a new major version (e.g., from `^1.x.x` to `2.x.x`) because major versions often introduce breaking changes.
To explicitly update to the latest major version (use with caution, check release notes for breaking changes):
npm install <package-name>@latest
To see which packages are outdated (i.e., have newer versions available outside your `package.json` range):
npm outdated
This command shows `Current`, `Wanted` (highest matching `package.json` range), and `Latest` versions.
The `scripts` section in `package.json` allows you to define custom commands to automate tasks, such as starting your application, running tests, or building your project.
Add entries to the `scripts` object in `package.json`:
# package.json
{
"name": "my-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js", // To start your app
"test": "jest", // To run tests
"dev": "nodemon index.js", // To run in development mode with auto-restart
"build": "webpack", // To build your project for production
"lint": "eslint .", // To run a linter
"hello": "echo Hello, npm!" // A simple custom script
},
"dependencies": { /* ... */ }
}
npm run <script-name>
Examples:
npm run start
npm run test
npm run dev
npm run build
npm run lint
npm run hello
For `start` and `test` scripts, `npm` provides shorthands:
npm start # Same as npm run start
npm test # Same as npm run test
Some tools are command-line utilities that you might want to use across multiple projects or system-wide (e.g., a CLI tool, a code formatter).
npm install -g <package-name>
Example: Installing `create-react-app` CLI tool
npm install -g create-react-app
Now, you can run `create-react-app` from any directory in your terminal.
create-react-app my-new-react-app
npm list -g --depth=0 # List top-level global packages
npm uninstall -g <package-name>
If you've created your own reusable JavaScript module, you can publish it to the npm registry for others (or yourself) to use.
npm login
Follow the prompts for username, password, and email.
npm publish
This command publishes the package to the public npm registry. If it's a scoped package (e.g., `@yourorg/mypackage`), you might need `--access public` for public scope if it's a new organization.
# Example package.json for publishing
{
"name": "my-utility-package",
"version": "1.0.0",
"description": "A simple utility function for calculations.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": ["utility", "math", "calculator"],
"author": "Your Name <your.email@example.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/your-username/my-utility-package.git"
}
}
The `npm audit` command checks your project's dependencies for known security vulnerabilities and provides recommendations for remediation.
npm audit
This will output a report detailing any vulnerabilities found, their severity, and affected packages.
npm can often automatically fix many vulnerabilities by updating packages to secure versions.
npm audit fix
For vulnerabilities that cannot be automatically fixed (e.g., requiring a major version upgrade with breaking changes), `npm audit` will provide manual remediation steps.
npm outdated
npm ls # List all installed local packages (tree view)
npm ls --depth=0 # List only top-level local packages
npm view express versions # View all available versions of express
npm view react main # View the main entry file for react
npm search cli-tool
npm cache verify # Verify the integrity of the cache folder's contents
npm doctor
# Instead of npm install -g create-react-app, then create-react-app my-app
npx create-react-app my-app # Downloads and runs create-react-app without global install
`npx` is great for running one-off CLI tools or ensuring you always use the latest version without managing global installs.
# Recommended fix for global install permissions (from npm docs):
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH # Add to your .bashrc or .zshrc
source ~/.bashrc # Or .zshrc
It's your gateway to a vast ecosystem of reusable code, allowing you to build robust applications more quickly and efficiently. By understanding these commands and best practices, you'll be well-equipped to manage dependencies effectively in any Node.js or frontend project.