Featured image of post Npm入门

Npm入门

简介

官网:https://www.npmjs.com/

NPM是Node.js包管理工具,相当于前端的Maven

1
2
# 在命令行输入npm -v 可查看当前npm版本
npm -v

快速开始

在项目目录下执行npm init初始化项目

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// 最终生成package.json文件
{
  "name": "npm",
  "version": "1.0.0",
  "description": "node project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node"
  ],
  "author": "satan",
  "license": "ISC"
}

安装模块

npm install 模块名 或 npm i 模块名(可以同时下载多个)

模块位置:项目下的node_moudules

1
2
3
4
5
# 注意 出现下载过慢或者无法下载的情况 ---  可以采用cnpm
npm install -g cnpm --registry=http://registry.npm.taobao.org

# 下载指定的版本号
npm install xxx@版本号

正式使用

执行 node + 文件.js 运行

1
2
3
4
5
6
7
8
// 导入模块redis
const redis = require("redis");
const client = redis.createClient();
client.on("error", function (error) {
  console.log(error);
});
client.set("key", "value", redis.print);
client.get("key", redis.print);
1
2
3
4
# 若出现ClientClosedError,可将redis版本降级
npm install redis@3.1.2 --save

# 注意 记得启动redis-server.exe

复用

  • 通过npm install xxx 的模块会记录在package.json这个文件中
  • 复用这个package.json,执行npm install 则能自动下载包含的模块

卸载模块

npm uninstall 模块名