Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

NPM Usage Introduction

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:

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

Global installation

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.

Additional Tags

Installation Examples


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:

How to use it:

  1. Initialize a project: run in the project directory npm init command, npm will guide you through creating a package.json file, or automatically generate one with default values for the package.json。

  2. Install dependencies: When using npm install command to install dependencies, npm will automatically add the dependencies to the package.json field of the dependencies or devDependencies , and create a package-lock.json file to lock the versions of dependencies.

  3. Managing scripts: In scripts Define commands in the "start": "node app.js", and then you can run them via the npm start command.

  4. Versioning: When using npm version command to manage the project's version number; npm will automatically update the package.json version number in it and create a new Git tag.

  5. Publishing a package: When the project is ready to be published to npm, you can use the npm publish command; npm will read the package.json information in it to publish the package.

  6. Dependency Management:package.json and package-lock.json files 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

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