NPM Usage Introduction
NPM is a package management tool that comes with NodeJS installation and addresses many issues related to NodeJS code deployment. Common usage scenarios include:
- Allowing users to download third-party packages written by others from the NPM server for local use.
- Allowing users to download and install command-line programs written by others from the NPM server for local use.
- Allowing users to upload their own packages or command-line programs to the NPM server for others to use.
Since the latest version of NodeJS already includes npm, it is installed along with NodeJS. You can test if it is installed successfully by entering "npm -v". The command and version prompt indicating successful installation are as follows:
$ npm -v
2.3.0
If you have an older version of npm, you can easily upgrade it using the npm command:
$ 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
For Windows systems, use the following command:
npm install npm -g
To use the Taobao mirror, use the command:
npm install -g cnpm --registry=https://registry.npmmirror.com
Installing Modules with npm Command
The syntax for installing Node.js modules using npm is as follows:
$ npm install <Module Name>
For example, to install the commonly used Node.js web framework module express:
$ npm install express
After installation, the express package is located in the node_modules directory under the project directory. Therefore, in the code, you only need to use require('express') without specifying the path of the third-party package.
var express = require('express');
Global vs. Local Installation
NPM package installation is divided into local (local) and global (global) installations. The difference in the command line is simply whether or not the -g flag is used, for example:
npm install express # Local installation
npm install express -g # Global installation
If you encounter the following error:
npm err! Error: connect ECONNREFUSED 127.0.0.1:8087
The solution is:
$ npm config set proxy null
Local Installation
- The package is installed in ./node_modules (the directory where the npm command is executed). If there is no node_modules directory, one will be created in the current directory where the npm command is executed.
- The package can be imported using require().
Global Installation
- The package is installed in /usr/local or your node installation directory.
- The package can be used directly in the command line.
If you want to have both functionalities, you need to install it in both places or use npm link.
Next, we install express globally:
$ npm install express -g
The installation process outputs the following content, with the first line indicating the module version 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])
Viewing Installed Modules
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 command as follows:
$ npm list grunt
projectName@projectVersion /path/to/project/folder
└── [email protected]
Using package.json
The package.json file is located in the module's directory and is used to define the package's properties. Let's take a look at the package.json file for the express package, located at node_modules/express/package.json:
{
"name": "express",
"description": "Fast, unopinionated, minimalist web framework",
"version": "4.13.3",
"author": {
"name": "TJ Holowaychuk",
"email": "[email protected]"
},
"contributors": [
{
"name": "Aaron Heckmann",
"email": "[email protected]"
},
{
"name": "Ciaran Jessup",
"email": "[email protected]"
},
{
"name": "Douglas Christopher Wilson",
"email": "[email protected]"
},
{
"name": "Guillermo Rauch",
"email": "[email protected]"
},
{
"name": "Jonathan Ong",
"email": "[email protected]"
},
{
"name": "Roman Shtylman",
"email": "[email protected]"
},
{
"name": "Young Jae Sim",
"email": "[email protected]"
}
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/strongloop/express.git"
},
"homepage": "http://expressjs.com/",
"keywords": [
"express",
"framework",
"sinatra",
"web",
"rest",
"restful",
"router",
"app",
"api"
],
"dependencies": {
"accepts": "~1.2.12",
"array-flatten": "1.1.1",
"content-disposition": "0.5.0",
"content-type": "~1.0.1",
"cookie": "0.1.3",
"cookie-signature": "1.0.6",
"debug": "~2.2.0",
"depd": "~1.0.1",
"escape-html": "1.0.2",
{
"dependencies": {
"etag": "~1.7.0",
"finalhandler": "0.4.0",
"fresh": "0.3.0",
"merge-descriptors": "1.0.0",
"methods": "~1.1.1",
"on-finished": "~2.3.0",
"parseurl": "~1.3.0",
"path-to-regexp": "0.1.7",
"proxy-addr": "~1.0.8",
"qs": "4.0.0",
"range-parser": "~1.0.2",
"send": "0.13.0",
"serve-static": "~1.10.0",
"type-is": "~1.6.6",
"utils-merge": "1.0.0",
"vary": "~1.0.1"
},
"devDependencies": {
"after": "0.8.1",
"ejs": "2.3.3",
"istanbul": "0.3.17",
"marked": "0.3.5",
"mocha": "2.2.5",
"should": "7.0.2",
"supertest": "1.0.1",
"body-parser": "~1.13.3",
"connect-redis": "~2.4.1",
"cookie-parser": "~1.3.5",
"cookie-session": "~1.2.0",
"express-session": "~1.11.3",
"jade": "~1.11.0",
"method-override": "~2.3.5",
"morgan": "~1.6.1",
"multiparty": "~4.1.2",
"vhost": "~3.0.1"
},
"engines": {
"node": ">= 0.10.0"
},
"files": [
"LICENSE",
"History.md",
"Readme.md",
"index.js",
"lib/"
],
"scripts": {
"test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/",
"test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/",
"test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/"
},
"gitHead": "ef7ad681b245fba023843ce94f6bcb8e275bbb8e",
"bugs": {
"url": "https://github.com/strongloop/express/issues"
},
"_id": "[email protected]",
"_shasum": "ddb2f1fb4502bf33588d2b032b037960ca6c80a3",
"_from": "express@*",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "[email protected]"
},
"maintainers": [
{
"name": "tjholowaychuk",
"email": "[email protected]"
},
{
"name": "jongleberry",
{
"contributors": [
{
"name": "jonathanrichardong",
"email": "[email protected]"
},
{
"name": "dougwilson",
"email": "[email protected]"
},
{
"name": "rfeng",
"email": "[email protected]"
},
{
"name": "aredridel",
"email": "[email protected]"
},
{
"name": "strongloop",
"email": "[email protected]"
},
{
"name": "defunctzombie",
"email": "[email protected]"
}
],
"dist": {
"shasum": "ddb2f1fb4502bf33598d2b032b037960ca6c80a3",
"tarball": "http://registry.npmjs.org/express/-/express-4.13.3.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/express/-/express-4.13.3.tgz",
"readme": "ERROR: No README data found!"
}
Package.json Properties Explanation
-
name - The package name.
-
version - The package version number.
-
description - The package description.
-
homepage - The package's official website URL.
-
author - The package author's name.
-
contributors - The names of other contributors to the package.
-
dependencies - The list of dependent packages. If the dependencies are not installed, npm will automatically install them in the node_modules directory.
-
repository - The type of repository where the package code is stored, which can be git or svn. Git repositories can be hosted on Github.
-
main - The main field specifies the primary entry file of the program. require('moduleName')
will load this file. The default value is the index.js file in the module's root directory.
-
keywords - Keywords
Uninstalling Modules
You can use the following command to uninstall Node.js modules.
$ npm uninstall express
After uninstalling, you can check if the package still exists in the /node_modules/ directory, or use the following command to check:
$ npm ls
Updating Modules
You can use the following command to update modules:
$ npm update express
Searching for Modules
Use the following command to search for modules:
$ npm search express
Creating Modules
Creating a module requires a package.json file. You can use NPM to generate a package.json file, which will include the basic structure.
$ 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) tutorialpro # Module name
version: (1.0.0)
description: Node.js test module(www.tutorialpro.org) # Description
entry point: (index.js)
test command: make test
Git repository: https://github.com/tutorialpro/tutorialpro.git # Github address keywords: author: license: (ISC) About to write to ……/node_modules/package.json: # Generated address
{ "name": "tutorialpro", "version": "1.0.0", "description": "Node.js test module (www.tutorialpro.org)", …… }
Is this ok? (yes) yes
You need to enter the above information based on 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 repository (using email registration):
$ npm adduser Username: mcmohd Password: Email: (this IS public) [email protected]
Next, we use the following command to publish the module:
$ npm publish
If you have performed the above steps correctly, you can install it like other modules using npm.
---
## Versioning
When downloading and publishing code using NPM, you will encounter version numbers. NPM uses semantic versioning to manage code. Here is a brief introduction.
Semantic versioning consists of three parts: X.Y.Z, representing the major, minor, and patch version numbers respectively. When code changes, the version number is updated according to the following principles:
- If only bugs are fixed, update the Z part.
- If new features are added but it is backward compatible, update the Y part.
- If there are major changes and it is not backward compatible, update the X part.
With this versioning assurance, when declaring third-party package dependencies, you can depend not only on a fixed version number but also on a range of version numbers. For example, "argv": "0.0.x" indicates a dependency on the latest version of the 0.0.x series of argv.
All version range specification methods supported by NPM can be found in the [official documentation](https://npmjs.org/doc/files/package.json.html#dependencies).
---
## Common NPM Commands
In addition to what is introduced in this chapter, NPM provides many other functions, and there are many other useful fields in package.json.
In addition to viewing the official documentation at [npmjs.org/doc/](https://npmjs.org/doc/), here are some common NPM commands.
NPM provides many commands, such as `install` and `publish`, and you can view all commands using `npm help`.
-
Use `npm help <command>` to view detailed help for a specific command, for example, `npm help install`.
-
Use `npm install . -g` in the directory where package.json is located to locally install the current command-line program, which can be used for local testing before publishing.
-
Use `npm update <package>` to update the corresponding module in the `node_modules` subdirectory to the latest version.
-
Use `npm update <package> -g` to update the globally installed command-line program to the latest version.
-
Use `npm cache clear` to clear the NPM local cache, which is useful for dealing with people who publish new versions of code with the same version number.
-
Use `npm unpublish <package>@<version>` to revoke a version of code that you have published.
---
## Using the Taobao NPM Mirror
Directly using the official NPM mirror in China is very slow, so it is recommended to use the Taobao NPM mirror.
The Taobao NPM mirror is a complete npmjs.org mirror, and you can use it as a replacement for the official version (read-only). The synchronization frequency is currently 10 minutes to ensure synchronization with the official service as much as possible.
You can use the Taobao-customized cnpm (gzip compression support) command-line tool instead of the default npm:
$ npm install -g cnpm --registry=https://registry.npmmirror.com
This allows you to use the cnpm command to install modules:
$ cnpm install [name] ```
More information can be found at: https://npmmirror.com/.