模块的分类
- 自定义模块
// 1. 创建模块
const name = {
id: 1,
name: 'Yan'
}
const str = 'sdaf'
// 2. 导出模块
// module.exports = name 只能导出一个
module.exports = { // 批量导出
name,
str
}
// 模块的导入
// const { name,str } = require(路径)
const { name,str } = require('./name.js')
console.log( name.name , str )
- 内置模块
const process = require('process')
const path = require('path')
console.log(process.version)
console.log(path.resolve('../'))
- 案例: 打包压缩包
- 流程:
- 读取文件
- 创建压缩包
- 将读取的数据流写入压缩包
- 输出压缩包
- 流程:
const fs = require('fs') // 读取yyb.txt文件
const zlib = require('zlib') // 创建压缩包
// const inp = fs.createReadStream( 路径 )
const inp = fs.createReadStream( './yyb.txt' ) //读出数据
const gzip = zlib.createGzip() // 创建压缩包
// const outp = fs.createWriteStream(路径)
const outp = fs.createWriteStream( './yyb.txt.gz' )//输出压缩包
inp
.pipe( gzip )
.pipe( outp )
- 第三方模块
我一般都是从npmjs.com这个网站拉取
使用流程:
1. 安装
先创建package.json 文件 (npm init -y)
npm/cnpm i request -S/-D (安装 request)
-S --save 生产环境
-D --save-dev dev development的简写 开发环境
2. 使用
request 这个模块是做数据请求
const request=require("request");
console.log(request)
request.get('http://api.douban.com/v2/movie/in_theaters', (err, response, body) => {
if (!err) {
// console.log(body);
console.log(JSON.parse(body))
} else {
console.log(err);
}
})
npm 使用入门
安装:无需安装
查看当前版本:
$ npm -v
更新:
$ npm install npm@latest -g
初始化工程
$ npm init
$ npm init --yes 默认配置
安装包
使用npm install会读取package.json文件来安装模块。安装的模块分为两类
dependencies和devDependencies,分别对应生产环境需要的安装包和开发环境需要的安装包。
$ npm install
$ npm install <package_name>
$ npm install <package_name> --save
$ npm install <package_name> --save-dev
更新模块
$ npm update
卸载模块
$ npm uninstall <package_name>
$ npm uninstall --save lodash
配置npm源
-
临时使用, 安装包的时候通过–registry参数即可
$ npm install express --registry https://registry.npm.taobao.org
-
全局使用
$ npm config set registry https://registry.npm.taobao.org // 配置后可通过下面方式来验证是否成功 npm config get registry // 或 npm info express
-
cnpm 使用
// 安装cnpm npm install -g cnpm --registry=https://registry.npm.taobao.org // 使用cnpm安装包 cnpm install express