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 project dependencies and tools.
NPM is a package management tool bundled with Node.js. Therefore, you usually only need to install Node.js, and NPM will be automatically installed on your system.

Main features:
Package management: NPM helps you install and manage various third-party libraries (packages) required by your project. For example, you can install, update, or delete dependencies with simple commands.
Version management: NPM supports version control, allowing you to lock a specific version of a dependency or choose the latest version as needed.
Package publishing: NPM allows developers to publish their own libraries to the NPM registry, and other developers can download and use these libraries via NPM.
Command-line tool: NPM provides a powerful command-line tool that can be used for various operations such as installing packages, running scripts, initializing projects, and more.
Since the latest version of Node.js already includes NPM, we can directly test it by enteringnpm -vto test whether it was installed successfully. If a version prompt appears, the installation was successful:
$ npm -v 2.3.0
If you have an older version of npm installed, you can easily upgrade it using the npm command. The command is as follows:
$ sudo npm install npm -g /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js [email protected] /usr/local/lib/node_modules/npm
If you are on a Windows system, you can use the following command:
npm install npm -g
Using npm commands to install modules
The syntax for npm to install a Node.js module is as follows:
$ npm install <Module Name>
In the following example, we use the npm command to install a common 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. Therefore, in your code you only need to userequire('express')in that way; there is no need to specify the path to the third-party package.
var express = require('express');
Global installation vs local installation
npm package installation is divided into two types: local installation and global installation. From the command line perspective, the only difference is whether there is a-gparameter.
Local installation:Installs the package into the node_modules directory and saves the information to the dependencies field in package.json.
npm install express # 本地安装
Global installation:Used to install command-line tools or packages that need to be used across 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 will install the package in the current project's
node_modulesfolder. This means each project that uses the package will have its own copy of the package. -
Purpose: Local installation is typically used for project dependencies. Each project can have its own dependency versions, which helps ensure project stability and reproducibility.
-
Installation command: Run in the project directory
npm install <package-name>will install the package in thenode_modulesfolder, andpackage.jsonadd the dependency to the file. -
Version management: Through the
package.jsonandpackage-lock.jsonfile, manage dependency versions to ensure consistency 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 used for tools or command-line utilities that do not need to be repeatedly installed in every project. For example, installing a global
create-react-appcan be used to create new React projects. -
Installation command: Use the
-gflag to install packages globally, for examplenpm install -g <package-name>。 -
Version management: The versions of globally installed packages are managed by npm, but they are not
package.jsonreflected in the project's. This means globally installed packages may be shared between different projects, but they may also cause problems due to version conflicts.
| Features | Local installation | Global installation |
|---|---|---|
| Installation scope | Only available in the current project | Available in the system-wide global environment |
| Command usage | npm install package-name | npm install -g package-name |
| Installation location | node_modulesdirectory | System global directory (varies by OS) |
| Use cases | Project dependencies (libraries, frameworks) | CLI tools, project generators |
| Access method | Byrequire()orimportusing | Directly used in the command line |
| Dependency declaration | Inpackage.jsonrecorded in | notpackage.jsonrecorded in |
| Version control | Different versions can be used in different projects | Only one version is kept in the system |
| Permission issues | No special permissions required | May require administrator permissions |
If you want to have both functionalities, you need to install it in both places or usenpm link。
Next, we will install express globally
$ npm install express -g
The installation process outputs the following content; the first line shows the module's version number and installation location.
[email protected] node_modules/express ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ([email protected]) ├── [email protected] ([email protected]) ├── [email protected] ([email protected], [email protected]) ├── [email protected] ([email protected]) ├── [email protected] ([email protected], [email protected]) ├── [email protected] ([email protected], [email protected]) └── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected])
View installed information
You can use the following command to view all globally installed modules:
$ npm list -g ├─┬ [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ └── [email protected] │ ├─┬ [email protected] │ │ └── [email protected] ……
To view the version number of a specific module, you can use the following command:
$ npm list grunt projectName@projectVersion /path/to/project/folder └── [email protected]
Uninstall modules
We can use the following command to uninstall a Node.js module.
$ npm uninstall express
After uninstalling, you can go to the /node_modules/ directory to check whether the package still exists, or use the following command to check:
$ npm ls
Update modules
We can use the following command to update a module:
$ npm update express
Search modules
Use the following to search for modules:
$ npm search express
Create modules
To create a module, the package.json file is essential. We can use NPM to generate a package.json file, and the generated file contains the basic result.
$ 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 <pkg> --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) example # 模块名
version: (1.0.0)
description: Node.js 测试模块(www.example.com) # 描述
entry point: (index.js)
test command: make test
git repository: https://github.com/example/example.git # Github 地址
keywords:
author:
license: (ISC)
About to write to ……/node_modules/package.json: # 生成地址
{
"name": "example",
"version": "1.0.0",
"description": "Node.js 测试模块(www.example.com)",
……
}
Is this ok? (yes) yes
You need to enter the above information according to your own situation. After entering "yes" at the end, a 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 address):
$ npm adduser Username: mcmohd Password: Email: (this IS public) [email protected]
Next, we will use the following command to publish the module:
$ npm publish
If all the above steps were performed correctly, you can use npm to install it just like other modules.
Version number
When using NPM to download and publish code, you will encounter version numbers. NPM uses semantic version numbers to manage code. Here is a brief introduction.
Version numbers follow Semantic Versioning (SemVer), with the format MAJOR.MINOR.PATCH, and may have additional labels attached.
- MAJOR (major version): Incremented when you make incompatible API changes. For example:
2.0.0。 - MINOR (minor version): Incremented when you add new functionality while maintaining backward compatibility. For example:
1.1.0。 - PATCH (patch version): Incremented when you fix bugs without adding new functionality. For example:
1.0.1。
Additional labels
- Pre-release version: such as
1.0.0-alphaor1.0.0-beta.1, indicating that this version is still in testing. - Build metadata: such as
1.0.0+build.1, which provides information about the build.
Installation examples
- Install a specific version:
npm install [email protected] - Install the latest major version:
npm install package-name@^1.2.3(install1.x.xthe latest version of)
NPM common commands
NPM provides many commands. You can usenpm helpto view all commands.
| Command | Description |
|---|---|
npm init | Initialize a newpackage.jsonfile, interactively inputting information. |
npm init -y | Quickly create apackage.jsonfile with default settings. |
npm install package-name | Install the specified package locally. |
npm install -g package-name | Install the specified package globally, making it available system-wide. |
npm install | Installpackage.jsonall dependencies listed in |
npm install package-name --save-dev | Install a package and add it todevDependencies。 |
npm update package-name | Update the specified dependency package. |
npm uninstall package-name | Uninstall the specified dependency package. |
npm uninstall -g package-name | Uninstall the specified package globally. |
npm list | View the list of installed dependency packages for the current project. |
npm list -g --depth=0 | View the list of globally installed dependency packages (without expanding the dependency tree). |
npm info package-name | View detailed information about a package, including version and dependencies. |
npm login | Log in to your NPM account. |
npm publish | Publish the current package to the NPM registry. |
npm unpublish package-name | Unpublish a package from the NPM registry (generally limited to within 24 hours). |
npm cache clean --force | Clean the NPM cache. |
npm audit | Check for security vulnerabilities in project dependencies. |
npm audit fix | Automatically fix known vulnerabilities. |
npm run script-name | Runpackage.jsonthe script defined in , for examplenpm run start。 |
npm start | Runstartscript (equivalent tonpm run start)。 |
npm test | Runtestscript. |
npm build | Runbuildscript. |
npm outdated | List dependency packages in the project that have available updates. |
npm version patch/minor/major | Updatepackage.jsonthe version number in , automatically updating the version. |
npm ci | Usepackage-lock.jsonto quickly install dependencies, suitable for CI/CD environments. |
Besides what is covered in this chapter, NPM provides many more features, and package.json also has many other useful fields.
Besides being able tohttps://docs.npmjs.com/view the official documentation at , here are some more commonly used NPM commands.
Using the Taobao NPM mirror
Since directly using npm's official mirror 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 downloading and installation.
The Taobao NPM mirror is a complete npmjs.org mirror. You can use it to replace the official version (read-only). The synchronization frequency is currently once every 10 minutes to ensure synchronization with the official service as much as possible.
You can use Taobao's customized cnpm (with gzip compression support) command-line tool to replace the default npm:
$ npm install -g cnpm --registry=https://registry.npmmirror.com
Next, we can use cnpm to replace npm for package installation and management:
$ cnpm install [name]
package.json description and usage
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 the project's metadata and dependency relationships. 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 name of the project, which should be unique, usually using lowercase letters and hyphens.version: The version number of the project, following Semantic Versioning.description: A brief description of the project.main: The entry file of the project, usually the application's startup file.scripts: Defines a series of command-line scripts that can execute specific tasks in the project.dependencies: Lists all dependency packages required for the project to run and their versions.devDependencies: Lists dependency packages and their versions needed only during development.peerDependencies: Lists packages that the project expects its dependency packages to also depend on.optionalDependencies: Lists optional dependency packages.engines: Specifies the Node.js version compatible with the project.repository: The project's code repository information, such as the URL of the GitHub repository.keywords: Keywords for the project, helpful for finding the project in npm search.author: The project's author information.license: The project's license information.
Usage:
-
Initialize the project: Run the
npm initcommand in the project directory, and npm will guide you to create apackage.jsonfile, or automatically generate apackage.json。 -
Install dependencies: Use the
npm install <package-name>command to install dependencies. npm will automatically add the dependencies topackage.jsonin the file'sdependenciesordevDependenciesand createpackage-lock.jsonfile to lock the dependency versions. -
Manage scripts: Define commands in the
scriptsfield, for example"start": "node app.js", and then you can use thenpm startcommand to run these scripts. -
Version control: Use the
npm versioncommand to manage the project's version number. npm will automatically update the version number inpackage.jsonand generate a new Git tag. -
Publish the package: When the project is ready to be published to npm, you can use the
npm publishcommand, and npm will read the information inpackage.jsonto publish the package. -
Dependency management:
package.jsonandpackage-lock.jsonwork together with the file to ensure consistent dependency versions across different environments.
A typical package.json file structure is as follows:
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 name of the project, usually lowercase letters and hyphens. |
| version | The version number of the project, followinglanguagemeaningtransformversionspecification (SemVer)。 |
| description | A brief description of the project. |
| main | The project's entry file, defaulting toindex.js。 |
| scripts | Defines executable script commands for the project, such asnpm start。 |
| dependencies | Dependency libraries required at runtime, added during installation tonode_modules。 |
| devDependencies | Dependency libraries used during development, not installed in production environments. |
| keywords | An array of keywords, helpful for describing the project and finding it in NPM search. |
| author | The project's author information. |
| license | The project's license type, such asMIT、ISC。 |
Benefits of using package.json
- Dependency management: Centrally manage the project's dependencies and their versions.
- Automating tasks: Through the
scriptsfield, you can conveniently run common tasks. - Version control: Ensure consistency of the project and its dependency versions, facilitating team collaboration.
- Describing the project: Provide metadata information for the project, making it easy to publish and share.
Dependency management
dependencies: Stores the dependencies required for the project to run.
"dependencies": {
"express": "^4.17.1"
}
When installing dependencies, use:
npm install express
devDependencies: Stores dependencies needed during project development.
"devDependencies": {
"nodemon": "^2.0.20"
}When installing dependencies, use:
npm install nodemon --save-dev
scripts field
The scripts field is used to define commands that can be executed via npm run <script>. Common scripts include:
"scripts": {
"start": "node app.js",
"test": "jest",
"build": "webpack --mode production",
"dev": "nodemon app.js"
}Example of running scripts:
npm run dev # 执行 "nodemon app.js" npm start # 等同于 "node app.js",可以直接用 npm start 运行
Explanation of symbols in version numbers
^(caret): Indicates installing the latest version compatible with the current major version. For example,^4.17.1will install4.x.xthe latest version in .~(tilde): Indicates installing the latest version compatible with the current minor version. For example,~4.17.1will install4.17.xthe latest version in .
Common commands
Initialize the package.json file:
npm init
Using npm init -y can quickly generate a default package.json file.
View project dependencies:
npm list --depth=0
Update dependencies:
npm update package-name
Notes
- Keep the
package.jsonfile concise and accurate, avoiding unnecessary fields. - Use
package-lock.jsonto lock dependency versions to ensure consistency of the project across different environments. - Regularly update dependencies to take advantage of the latest features and security fixes.
For more information, refer to:https://npmmirror.com/。
Other extensions