NPM Usage Introduction
NPM (Node Package Manager) is a JavaScript package management tool and the default package manager for Node.js.
NPM allows developers to easily download, install, share, and manage a project's dependency libraries and tools.
NPM is a package management tool bundled with Node.js, so normally you only need to install Node.js and NPM will be automatically installed on the system.

Main features:
-
Package Management: NPM can help you install and manage the various third-party libraries (packages) required by a project. For example, you can install, update, or remove dependencies with simple commands.
-
Version Management: NPM supports version control, allowing you to lock a dependency to a specific version or choose the latest version as needed.
-
Package Publishing: NPM allows developers to publish their own libraries to the NPM repository, and other developers can download and use these libraries through NPM.
-
command line tool: NPM provides powerful command-line tools that can be used for installing packages, running scripts, initializing projects, and other operations.
Since newer versions of Node.js already integrate NPM, we can test whether the installation was successful by simply typing npm -v; a version prompt indicates a successful installation:
$ npm -v
2.3.0
If you have an older version of npm installed, you can easily upgrade it via the npm command, as follows:
$ sudo npm install npm -g
/usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
npm@2.14.2 /usr/local/lib/node_modules/npm
If you are using a Windows system, just use the following command:
npm install npm -g
Install modules using the npm command
The syntax for installing Node.js modules with npm is as follows:
$ npm install
In the following example, we use the npm command to install a commonly used Node.js web framework module express:
$ npm install express
After installation, the express package is placed in the node_modules directory under the project directory, so in the code you only need to use require('express') and there is no need to specify the third-party package path.
var express = require('express');
Global Installation vs. Local Installation
npm package installation is divided into two types: local installation (local) and global installation (global). From the command line, the only difference is whether the -g parameter is present.
**Local installation:** install the package into the node_modules directory and save the information to dependencies in package.json.
npm install express # 本地安装
**Global installation:** used to install command-line tools or packages that need to be used in multiple projects.
npm install express -g # 全局安装
If the following error occurs:
npm err! Error: connect ECONNREFUSED 127.0.0.1:8087
The solution is:
$ npm config set proxy null
Local Installation
-
Scope: by default, npm installs packages in the current project's
node_modulesfolder. This means every project using the package will have its own copy of it. -
Purpose: local installation is typically used for project dependencies. Each project can have its own dependency versions, which helps ensure project stability and reproducibility.
-
Install Command: run in the project directory
npm installwill install the package in thenode_modulesfolder, and add the dependency to thepackage.jsonfile. -
Version Management: Through
package.jsonandpackage-lock.jsonThe file manages dependency versions, ensuring consistency of the project across different environments.
Global installation
-
Scope: global installation installs packages in a system-level directory, usually
/usr/local/bin(on Unix-like systems) or%AppData%\npm(on Windows). -
Purpose: global installation is for tools or command-line utilities that do not need to be reinstalled in every project. For example, installing a global
create-react-appcan be used to create new React projects. -
Install Command: When using
-gflag to install packages globally, for examplenpm install -g。 -
Version Management: globally installed package versions are managed by npm, but are not reflected in the project's
package.jsonThis means globally installed packages may be shared between different projects, but may also cause problems due to version conflicts.
| Feature | Local Installation | Global installation |
|---|---|---|
| Installation Scope | Available only in the current project | Available in the system's global environment |
| Command Usage | npm install package-name |
npm install -g package-name |
| Installation Location | node_modules directory |
System global directory (varies by OS) |
| Use Cases | Project dependencies (libraries, frameworks) | CLI tools, project generators |
| Access Method | Pass require() or import Use |
Use directly on the command line |
| dependency declaration | in package.json recorded in |
not in package.json recorded in |
| Versioning | Different versions can be used in different projects | Only one version is kept in the system |
| Permission issues | No special permissions required | Administrator privileges may be required |
If you want both features, you need to install it in both places or use npm link。
Next we will install express globally
$ npm install express -g
The installation process outputs the following; the first line shows the module's version number and installation location.
express@4.13.3 node_modules/express
├── escape-html@1.0.2
├── range-parser@1.0.2
├── merge-descriptors@1.0.0
├── array-flatten@1.1.1
├── cookie@0.1.3
├── utils-merge@1.0.0
├── parseurl@1.3.0
├── cookie-signature@1.0.6
├── methods@1.1.1
├── fresh@0.3.0
├── vary@1.0.1
├── path-to-regexp@0.1.7
├── content-type@1.0.1
├── etag@1.7.0
├── serve-static@1.10.0
├── content-disposition@0.5.0
├── depd@1.0.1
├── qs@4.0.0
├── finalhandler@0.4.0 (unpipe@1.0.0)
├── on-finished@2.3.0 (ee-first@1.1.1)
├── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)
├── debug@2.2.0 (ms@0.7.1)
├── type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.6)
├── accepts@1.2.12 (negotiator@0.5.3, mime-types@2.1.6)
└── send@0.13.0 (destroy@1.0.3, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http-errors@1.3.1)
View Installation Information
You can use the following command to view all globally installed modules:
$ npm list -g
├─┬ cnpm@4.3.2
│ ├── auto-correct@1.0.0
│ ├── bagpipe@0.3.5
│ ├── colors@1.1.2
│ ├─┬ commander@2.9.0
│ │ └── graceful-readlink@1.0.1
│ ├─┬ cross-spawn@0.2.9
│ │ └── lru-cache@2.7.3
……
To view the version number of a module, use the following command:
$ npm list grunt
projectName@projectVersion /path/to/project/folder
└── grunt@0.4.1
Unload a module
We can use the following command to uninstall a Node.js module.
$ npm uninstall express
After uninstalling, you can check whether the package still exists in the /node_modules/ directory, or use the following command to check:
$ npm ls
Update Modules
We can use the following command to update modules:
$ npm update express
Search Modules
Use the following to search for modules:
$ npm search express
Creating a module
To create a module, the package.json file is essential. We can use NPM to generate a package.json file; the generated file contains basic results.
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (node_modules) runoob # 模块名
version: (1.0.0)
description: Node.js 测试模块(www.runoob.com) # 描述
entry point: (index.js)
test command: make test
git repository: https://github.com/runoob/runoob.git # Github 地址
keywords:
author:
license: (ISC)
About to write to ……/node_modules/package.json: # 生成地址
{
"name": "runoob",
"version": "1.0.0",
"description": "Node.js 测试模块(www.runoob.com)",
……
}
Is this ok? (yes) yes
You need to enter the above information according to your own situation. After entering "yes" at the end, the package.json file will be generated.
Next we can use the following command to register a user in the npm registry (register with an email):
$ npm adduser
Username: mcmohd
Password:
Email: (this IS public) mcmohd@gmail.com
Next we use the following command to publish the module:
$ npm publish
If you performed all the above steps correctly, you can install it with npm just like any other module.
Version number
When downloading and publishing code with NPM you will encounter version numbers. NPM uses semantic version numbers to manage code; here is a brief introduction.
Version numbers follow Semantic Versioning (SemVer), in the format MAJOR.MINOR.PATCH, and may include additional tags.
- MAJOR (major version): increased when you make incompatible API changes. For example:
2.0.0。 - MINOR (minor version): increased when you add new functionality while maintaining backward compatibility. For example:
1.1.0。 - PATCH (patch version): increased when you fix bugs without adding new functionality. For example:
1.0.1。
Additional Tags
- Prerelease versions: Such as
1.0.0-alphaor1.0.0-beta.1, indicating that the version is still in testing. - Build metadata: Such as
1.0.0+build.1, providing information about the build.
Installation Examples
- Install a specific version:
npm install package-name@1.2.3 - Install the latest major version:
npm install package-name@^1.2.3Install1.x.x(install
the latest version)
Common NPM Commands
| Command | Description |
|---|---|
npm init |
NPM provides many commands; you can use npm help to view all commands. package.json Initialize a new |
npm init -y |
file, interactively entering information. package.json files. |
npm install package-name |
Quickly create one with default settings |
npm install -g package-name |
Locally install a specified package. |
npm install |
Installation package.json Globally install a specified package, making it available system-wide. |
npm install package-name --save-dev |
All dependencies listed in it. devDependencies。 |
npm update package-name |
Install a package and add it to |
npm uninstall package-name |
Update the specified dependency package. |
npm uninstall -g package-name |
Uninstall the specified dependency package. |
npm list |
Globally uninstall the specified package. |
npm list -g --depth=0 |
View the list of installed dependencies in the current project. |
npm info package-name |
View the list of globally installed dependency packages (without expanding the dependency tree). |
npm login |
View detailed information about a package, including its version and dependencies. |
npm publish |
Log in to an NPM account. |
npm unpublish package-name |
Publish the current package to the NPM registry. |
npm cache clean --force |
Unpublish a package from the NPM registry (generally within 24 hours). |
npm audit |
Clean the NPM cache. |
npm audit fix |
Check project dependencies for security vulnerabilities. |
npm run script-name |
Run package.json Automatically fix known vulnerabilities. npm run start。 |
npm start |
Run start scripts defined in it, for example npm run start)。 |
npm test |
Run test script (equivalent to |
npm build |
Run build script (equivalent to |
npm outdated |
script. |
npm version patch/minor/major |
update package.json List dependency packages in the project that have newer versions available. |
npm ci |
Use package-lock.json version numbers in it, automatically updating versions. |
Quickly install dependencies, suitable for CI/CD environments.
Besides being able to visit https://docs.npmjs.com/ the official documentation, here we introduce some additional commonly used NPM commands.
Using the Taobao NPM Mirror
Since using npm's official mirror directly in China is very slow, to solve this problem we can use the mirror provided by Taobao (cnpm or by configuring NPM) to speed up package downloads and installations.
The Taobao NPM mirror is a complete npmjs.org mirror that you can use in place of the official version (read-only); the sync frequency is currently once every 10 minutes to ensure it stays as synchronized as possible with the official service.
You can use the Taobao customized cnpm (with gzip compression support) command-line tool in place of the default npm:
$ npm install -g cnpm --registry=https://registry.npmmirror.com
Next we can use cnpm instead of npm for package installation and management:
$ cnpm install [name]
Description and Usage of package.json
package.json is a core file in a Node.js project, containing the project's metadata, dependencies, scripts, and other information.
The package.json file is used to describe a project's metadata and dependencies; it is usually located in the project's root directory and serves as the project's configuration file.
The package.json file is a JSON-format file containing the following basic fields:
name: the project's name, which should be unique and typically uses lowercase letters and hyphens.version: the project's version number, following Semantic Versioning.description: a brief description of the project.main: the project's entry file, usually the startup file of the application.scripts: defines a set of command-line scripts that can perform specific tasks in the project.dependencies: lists all dependency packages and their versions required for the project to run.devDependencies: lists dependency packages and their versions needed only during development.peerDependencies: lists packages that the project expects its dependencies to also depend on.optionalDependencies: lists optional dependency packages.engines: specifies the Node.js versions with which the project is compatible.repository: The project's code repository information, such as the URL of a GitHub repository.keywords: The project's keywords, which help users find the project in npm searches.author: The project's author information.license: The project's license information.
How to use it:
-
Initialize a project: run in the project directory
npm initcommand, npm will guide you through creating apackage.jsonfile, or automatically generate one with default values for thepackage.json。 -
Install dependencies: When using
npm installcommand to install dependencies, npm will automatically add the dependencies to thepackage.jsonfield of thedependenciesordevDependencies, and create apackage-lock.jsonfile to lock the versions of dependencies. -
Managing scripts: In
scriptsDefine commands in the"start": "node app.js", and then you can run them via thenpm startcommand. -
Versioning: When using
npm versioncommand to manage the project's version number; npm will automatically update thepackage.jsonversion number in it and create a new Git tag. -
Publishing a package: When the project is ready to be published to npm, you can use the
npm publishcommand; npm will read thepackage.jsoninformation in it to publish the package. -
Dependency Management:
package.jsonandpackage-lock.jsonfiles work together to ensure consistent dependency versions across different environments.
A typical package.json file has the following structure:
Example
{
"name"
:
"my-project"
,
"version"
:
"1.0.0"
,
"description"
:
"A simple Node.js project"
,
"main"
:
"app.js"
,
"scripts"
:
{
"start"
:
"node app.js"
,
"test"
:
"echo "Error: no test specified" && exit 1"
}
,
"dependencies"
:
{
"express"
:
"^4.17.1"
}
,
"devDependencies"
:
{
"nodemon"
:
"^2.0.20"
}
,
"keywords"
:
[
"node"
,
"npm"
,
"example"
]
,
"author"
:
"Your Name"
,
"license"
:
"MIT"
}
Field descriptions:
| Field | Description |
|---|---|
| name | The project's name, usually in lowercase letters and hyphens. |
| version | The project's version number, following the Semantic Versioning specification (SemVer)。 |
| description | A brief description of the project. |
| main | The project's entry file, defaulting to index.js。 |
| scripts | Defines executable script commands for the project, such as npm start。 |
| dependencies | Libraries required at runtime by the project, added during installation to node_modules。 |
| devDependencies | Libraries used during development, not installed in production environments. |
| keywords | An array of keywords that help describe the project and make it findable in NPM searches. |
| author | The project's author information. |
| license | The project's license type, such as MIT、ISC。 |
Benefits of using package.json
- Dependency Management: Centrally manages the project's dependencies and their versions.
- Automation Tasks: Through
scriptsfields make it convenient to run common tasks. - Versioning: Ensures consistency of the project and its dependency versions, making team collaboration easier.
- Describing the project: Provides metadata for the project, making it easier to publish and share.
Dependency Management
dependencies: Stores the dependencies required to run the project.
"dependencies": {
"express": "^4.17.1"
}
When installing dependencies, use:
npm install express
devDependencies: Stores the dependencies needed during project development.
"devDependencies": {
"nodemon": "^2.0.20"
}
When installing dependencies, use:
npm install nodemon --save-dev
The scripts field
The scripts field is used to define commands that can be run via npm run