npm 安裝 Node.js 模塊語(yǔ)法格式如下:
$ npminstall
以下實(shí)例,我們使用 npm 命令安裝常用的 Node.js web框架模塊express:
$npm install express
安裝好之后,express 包就放在了工程目錄下的 node_modules 目錄中,因此在代碼中只需要通過require('express')的方式就好,無需指定第三方包路徑。
varexpress =require('express');
全局安裝與本地安裝
npm 的包安裝分為本地安裝(local)、全局安裝(global)兩種,從敲的命令行來看,差別只是有沒有-g而已,比如
npminstall express# 本地安裝npm install express -g# 全局安裝
本地安裝
1. 將安裝包放在 ./node_modules 下(運(yùn)行 npm 命令時(shí)所在的目錄),如果沒有 node_modules 目錄,會(huì)在當(dāng)前執(zhí)行 npm 命令的目錄下生成 node_modules 目錄。
2. 可以通過 require() 來引入本地安裝的包。
全局安裝
1. 將安裝包放在 /usr/local 下或者你 node 的安裝目錄。
2. 可以直接在命令行里使用。

你可以使用以下命令來查看所有全局安裝的模塊:
$npm ls -g
使用 package.json
package.json 位于模塊的目錄下,用于定義包的屬性。接下來讓我們來看下 express 包的 package.json 文件,位于 node_modules/express/package.json
Package.json 屬性說明
name- 包名。
version- 包的版本號(hào)。
description- 包的描述。
homepage- 包的官網(wǎng) url 。
author- 包的作者姓名。
contributors- 包的其他貢獻(xiàn)者姓名。
dependencies- 依賴包列表。如果依賴包沒有安裝,npm 會(huì)自動(dòng)將依賴包安裝在 node_module 目錄下。
repository- 包代碼存放的地方的類型,可以是 git 或 svn,git 可在 Github 上。
main- main 字段是一個(gè)模塊ID,它是一個(gè)指向你程序的主要項(xiàng)目。就是說,如果你包的名字叫 express,然后用戶安裝它,然后require("express")。
keywords- 關(guān)鍵字
卸載模塊
我們可以使用以下命令來卸載 Node.js 模塊。
$npm uninstall express
卸載后,你可以到 /node_modules/ 目錄下查看包是否還存在,或者使用以下命令查看:
$npm ls
更新模塊
我們可以使用以下命令更新模塊:
$ npmupdateexpress
搜索模塊
使用以下來搜索模塊:
$npm search express
創(chuàng)建模塊
創(chuàng)建模塊,package.json 文件是必不可少的。我們可以使用 NPM 生成 package.json 文件,生成的文件包含了基本的結(jié)果。
$ npm initThis utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sensible defaults.See `npmhelpjson` for definitive documentation on these fields
and exactly what they do.
Use `npminstall--save` afterwards to install a package andsaveitasa dependencyinthe package.json file.Press ^Catanytimetoquit.name: (node_modules) runoob? ? ? ? ? ? ? ? ? # 模塊名version: (1.0.0) description: Node.js 測(cè)試模塊(www.runoob.com)? # 描述entry point: (index.js)testcommand: maketestgit repository: https://github.com/runoob/runoob.git? # Github 地址keywords: author: license: (ISC) Abouttowriteto……/node_modules/package.json:? ? ? # 生成地址{"name":"runoob","version":"1.0.0","description":"Node.js 測(cè)試模塊(www.runoob.com)",? ……}Isthis ok? (yes) yes
以上的信息,你需要根據(jù)你自己的情況輸入。在最后輸入 "yes" 后會(huì)生成 package.json 文件。