说说包管理工具 NPM 的基本用法

NPM 是随同 NodeJS 一起安装的包管理工具,可以解决 NodeJS 代码部署上的很多问题,常见的使用场景有以下几种:

  1. 允许我们从 NPM 服务器下载第三方编写的包到本地使用。
  2. 允许我们从 NPM 服务器下载并安装第三方编写的命令行程序到本地使用。
  3. 允许我们将自己编写的包或命令行程序上传到 NPM 服务器供他人使用。

新版的 nodejs 已经集成了 npm ,所以 npm 不需要单独安装。

1 淘宝 NPM 镜像

因为国内直接使用 npm 的官方镜像非常慢,所以推荐使用淘宝 NPM 镜像。这是一个完整 npmjs.org 镜像,我们可以用此代替官方版本(只读),同步频率目前为 10分钟 一次,保证与官方服务同步。

安装指令:

npm install -g cnpm --registry=http://registry.npm.taobao.org

也可以用此指令,更新淘宝 NPM 镜像包。

安装成功后,就可以使用 cnpm 命令来安装模块了:

cnpm install [name]

淘宝 NPM 镜像完整说明:http://npm.taobao.org/

2 安装模块

npm 安装 Node.js 模块语法格式如下:

npm install <Module Name>

比如想安装 request 模块,就可以这样:

npm install request

不过还是建议用 cnpm 指令来安装模块,会更快些。

然后就可以通过 require 调用我们刚刚安装的模块。在 WebStorm 中,会弹出提示,让我们把模块写到 package.json 文件中。


通过 Alt + Shift + Enter 指令,就可以自动创建 package.json 文件并添加好对应的模块:

{
  "name": "deniro-nodejs",
  "version": "1.0.0",
  "dependencies": {
    "request": "latest"
  }
}

3 全局安装与本地安装

npm 的包安装分为本地安装(local)、全局安装(global)两种,全局安装命令比本地安装命令,多了一个 -g

cnpm install request  # 本地安装
cnpm install request -g #全局安装

二者区别如下:

安装包路径 调用方式
本地安装 放在 ./node_modules 下(运行 npm 命令时所在的目录),如果没有 node_modules 目录,会在当前执行 npm 命令的目录下生成 node_modules 目录。 通过 require() 来引入本地安装的包。
全局安装 放在 /usr/local 下或者 node.js 的安装目录。 可以直接在命令行里使用。

全局安装 request 模块时,会输出如下内容:

[1/20] aws-sign2@~0.7.0 installed at node_modules\_aws-sign2@0.7.0@aws-sign2
[2/20] aws4@^1.8.0 installed at node_modules\_aws4@1.9.1@aws4
[3/20] caseless@~0.12.0 installed at node_modules\_caseless@0.12.0@caseless
[4/20] is-typedarray@~1.0.0 installed at node_modules\_is-typedarray@1.0.0@is-typedarray
[5/20] forever-agent@~0.6.1 installed at node_modules\_forever-agent@0.6.1@forever-agent
[6/20] isstream@~0.1.2 installed at node_modules\_isstream@0.1.2@isstream
[7/20] oauth-sign@~0.9.0 installed at node_modules\_oauth-sign@0.9.0@oauth-sign
[8/20] performance-now@^2.1.0 installed at node_modules\_performance-now@2.1.0@performance-now
[9/20] json-stringify-safe@~5.0.1 installed at node_modules\_json-stringify-safe@5.0.1@json-stringify-safe
[10/20] combined-stream@~1.0.6 installed at node_modules\_combined-stream@1.0.8@combined-stream
[11/20] form-data@~2.3.2 installed at node_modules\_form-data@2.3.3@form-data
[12/20] extend@~3.0.2 installed at node_modules\_extend@3.0.2@extend
[13/20] qs@~6.5.2 installed at node_modules\_qs@6.5.2@qs
[14/20] mime-types@~2.1.19 installed at node_modules\_mime-types@2.1.26@mime-types
[15/20] safe-buffer@^5.1.2 installed at node_modules\_safe-buffer@5.2.0@safe-buffer
[16/20] tunnel-agent@^0.6.0 installed at node_modules\_tunnel-agent@0.6.0@tunnel-agent
[17/20] uuid@^3.3.2 installed at node_modules\_uuid@3.4.0@uuid
[18/20] tough-cookie@~2.5.0 installed at node_modules\_tough-cookie@2.5.0@tough-cookie
[19/20] har-validator@~5.1.3 installed at node_modules\_har-validator@5.1.3@har-validator
[20/20] http-signature@~1.2.0 installed at node_modules\_http-signature@1.2.0@http-signature
All packages installed (47 packages installed from npm registry, used 1s(network 1s), speed 857.68kB/s, json 46(93.67kB), tarball 968.13kB)

4 常用指令

(1)查看所有全局安装的模块

npm list -g

输出形如:

| | | +-- aproba@2.0.0 deduped
| | | +-- figgy-pudding@3.5.1 deduped
| | | `-- npm-registry-fetch@4.0.3 deduped
| | +-- npm-registry-fetch@4.0.3
| | | +-- bluebird@3.5.5 deduped
| | | +-- figgy-pudding@3.5.1 deduped
| | | +-- JSONStream@1.3.5 deduped
| | | +-- lru-cache@5.1.1 deduped
...

(2)查看某个模块的版本号

npm list [name]

输出形如:

deniro-nodejs@1.0.0 F:\WebstormProjects\deniro-nodejs
`--  request@2.88.2

输出格式为:projectName@projectVersion /path/to/project/folder。

(3)更新模块指令

npm update [name]

(4)搜索模块指令

npm search [name]

比如搜索 request 模块,会输出以下内容:

NAME                      | DESCRIPTION          | AUTHOR          | DATE       | VERSION  | KEYWORDS

superagent                | elegant & feature…   | =defunctzombie… | 2020-02-17 | 5.2.2    | agent ajax ajax api async await axios cancel client frisbee got http http h
tt
request-promise           | The simplified HTTP… | =analog-nico…   | 2019-11-04 | 4.2.5    | xhr http https promise request then thenable bluebird
request-promise-native    | The simplified HTTP… | =analog-nico…   | 2019-11-04 | 1.0.8    | xhr http https promise request then thenable native
needle                    | The leanest and…     | =tomas          | 2020-04-03 | 2.4.1    | http https simple request client multipart upload proxy deflate timeout char
s
request-progress          | Tracks the download… | =satazor        | 2016-12-01 | 3.0.0    | progress request mikeal size bytes percent percentage speed eta etr
supertest                 | SuperAgent driven…   | =defunctzombie… | 2019-03-15 | 4.0.2    | superagent request tdd bdd http test testing
got                       | Human-friendly and…  | =sindresorhus…  | 2020-03-24 | 10.7.0   | http https http2 get got url uri request simple curl wget fetch net network
 e
graphql-request           | [![CircleCI](https:… | =schickling…    | 2018-08-10 | 1.8.2    | graphql request fetch graphql-client apollo
morgan                    | HTTP request logger… | =dougwilson     | 2020-03-20 | 1.10.0   | express http logger middleware
axios-mock-adapter        | Axios adapter that…  | =ctimmerm       | 2020-03-22 | 1.18.1   | axios test mock request stub adapter
cookie-parser             | Parse HTTP request…  | =defunctzombie… | 2020-03-15 | 1.4.5    | cookie middleware
raf                       | requestAnimationFra… | =chrisdickinson… | 2018-11-02 | 3.4.1    | requestAnimationFrame polyfill
request-promise-core      | Core Promise…        | =analog-nico    | 2019-11-03 | 1.1.3    | xhr http https promise request then thenable core
popsicle                  | Advanced HTTP…       | =blakeembrey    | 2019-11-03 | 12.0.5   | request http middleware node ajax browser promise
sync-request              | Make synchronous…    | =forbeslindesay | 2019-03-17 | 6.1.0    | request http https cache browserify synchronous sync
http-signature            | Reference…           | =arekinath…     | 2020-04-02 | 1.3.4    | https request
cacheable-request         | Wrap native HTTP…    | =lukechilds     | 2020-01-21 | 7.0.1    | HTTP HTTPS cache caching layer cacheable RFC 7234 RFC 7234 compliant
light-my-request          | Fake HTTP injection… | =delvedor…      | 2020-03-26 | 3.7.4    | http inject fake request server
proxy-addr                | Determine address…   | =dougwilson     | 2020-02-24 | 2.0.6    | ip proxy x-forwarded-for
make-fetch-happen         | Opinionated,…        | =ruyadorno…     | 2020-03-12 | 8.0.4    | http request fetch mean girls caching cache subresource integrity




(5)查看 npm 版本号

npm -v

5 package.json

package.json 位于模块包的根目录下(模块安装成功后,会放在 node_modules 下),用于定义模块包的属性。比如,request 模块的 package.json 配置如下:

{
  "name": "request",
  "description": "Simplified HTTP request client.",
  "keywords": [
    "http",
    "simple",
    "util",
    "utility"
  ],
  "version": "2.88.2",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com>",
  "repository": {
    "type": "git",
    "url": "https://github.com/request/request.git"
  },
  "bugs": {
    "url": "http://github.com/request/request/issues"
  },
  "license": "Apache-2.0",
  "engines": {
    "node": ">= 6"
  },
  "main": "index.js",
  "files": [
    "lib/",
    "index.js",
    "request.js"
  ],
  "dependencies": {
    "aws-sign2": "~0.7.0",
    "aws4": "^1.8.0",
    "caseless": "~0.12.0",
    "combined-stream": "~1.0.6",
    "extend": "~3.0.2",
    "forever-agent": "~0.6.1",
    "form-data": "~2.3.2",
    "har-validator": "~5.1.3",
    "http-signature": "~1.2.0",
    "is-typedarray": "~1.0.0",
    "isstream": "~0.1.2",
    "json-stringify-safe": "~5.0.1",
    "mime-types": "~2.1.19",
    "oauth-sign": "~0.9.0",
    "performance-now": "^2.1.0",
    "qs": "~6.5.2",
    "safe-buffer": "^5.1.2",
    "tough-cookie": "~2.5.0",
    "tunnel-agent": "^0.6.0",
    "uuid": "^3.3.2"
  },
  "scripts": {
    "test": "npm run lint && npm run test-ci && npm run test-browser",
    "test-ci": "taper tests/test-*.js",
    "test-cov": "nyc --reporter=lcov tape tests/test-*.js",
    "test-browser": "node tests/browser/start.js",
    "lint": "standard"
  },
  "devDependencies": {
    "bluebird": "^3.2.1",
    "browserify": "^13.0.1",
    "browserify-istanbul": "^2.0.0",
    "buffer-equal": "^1.0.0",
    "codecov": "^3.0.4",
    "coveralls": "^3.0.2",
    "function-bind": "^1.0.2",
    "karma": "^3.0.0",
    "karma-browserify": "^5.0.1",
    "karma-cli": "^1.0.0",
    "karma-coverage": "^1.0.0",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma-tap": "^3.0.1",
    "nyc": "^14.1.1",
    "phantomjs-prebuilt": "^2.1.3",
    "rimraf": "^2.2.8",
    "server-destroy": "^1.0.1",
    "standard": "^9.0.0",
    "tape": "^4.6.0",
    "taper": "^0.5.0"
  },
  "greenkeeper": {
    "ignore": [
      "hawk",
      "har-validator"
    ]
  },
  "__npminstall_done": "Sat Apr 18 2020 10:38:30 GMT+0800 (GMT+08:00)",
  "_from": "request@2.88.2",
  "_resolved": "https://registry.npm.taobao.org/request/download/request-2.88.2.tgz?cache=0&sync_timestamp=1581439349114&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Frequest%2Fdownload%2Frequest-2.88.2.tgz"
}

具体属性说明如下:

属性 说明
name 包名。
version 包的版本号。
description 描述。
homepage 官网主页 url 。
author 作者姓名。
contributors 贡献者姓名。
dependencies 依赖包列表。如果依赖包没有安装,npm 会自动将依赖包安装在 node_module 目录下。
repository 包代码托管类型,可以是 git 或 svn,git 可在 Github 上。
main 指定了程序的主入口文件,require('moduleName') 就会加载这个文件。这个字段的默认值是模块根目录下面的 index.js。
keywords 关键字

6 创建模块

我们所开发的项目,其实本质上也是模块,因此也是通过 npm 进行管理的。

我们可以使用 NPM 生成 package.json 文件,生成的文件包含了这个项目的一些基本的内容。

创建模块指令为:npm init,执行过程中会以交互的方式,让我们输入包名、版本号、描述、入口文件、测试命令、git 仓库地址、关键字、作者、许可证等信息。必填项会提供默认值,我们可以修改这些默认值。

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>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (deniro-nodejs)
version: (1.0.0)
description: study node.js
entry point: (create_app.js) index.js
test command: make test
git repository:
keywords:
author: Deniro Lee
license: (ISC)
About to write to F:\WebstormProjects\deniro-nodejs\package.json:

{
  "name": "deniro-nodejs",
  "version": "1.0.0",
  "dependencies": {
    "request": "latest"
  },
  "description": "study node.js",
  "main": "index.js",
  "devDependencies": {},
  "scripts": {
    "test": "make test"
  },
  "author": "Deniro Lee",
  "license": "ISC"
}


Is this OK? (yes) yes

执行后,就会在 package.json 中,加入以上这些配置项:

{
  "name": "deniro-nodejs",
  "version": "1.0.0",
  "dependencies": {
    "request": "latest"
  },
  "description": "study node.js",
  "main": "index.js",
  "devDependencies": {},
  "scripts": {
    "test": "make test"
  },
  "author": "Deniro Lee",
  "license": "ISC"
}

7 版本号

使用 NPM 下载和发布代码时都会接触到版本号。 NPM 使用语义版本号来管理代码。语义版本号分为 X.Y.Z 三位,分别代表主版本号 、 次版本号和补丁版本号。当代码变更时,版本号按以下原则更新。

  1. 如果只是修复 bug ,需要更新 Z 位;
  2. 如果是新增了功能,但是向下兼容,需要更新 Y 位;
  3. 如果有大变动,向下不兼容,需要更新 X 位。
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,440评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,814评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,427评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,710评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,625评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,014评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,511评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,162评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,311评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,262评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,278评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,989评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,583评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,664评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,904评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,274评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,856评论 2 339

推荐阅读更多精彩内容