阅读 22

说说包管理工具 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 镜像完整说明: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 位。
关注下面的标签,发现更多相似文章
评论