- 什么是流? Node中为什么要有流这个概念 ? 使用场景?
- 流指的是数据流,指的是数据是分片传输
- 数据可以实现非阻塞
- gulp 【 流式操作 】
- fs 获取文件夹文件内容
const fs = require( 'fs' ) fs.readFile('./yyb.txt',( error, docs ) => { console.log( docs.toString() ) }) fs.readFile('./yyb.txt','utf8',( error, docs ) => { console.log( docs.toString() ) })
- zlib
- 通过使用fs与zlib的实现压缩
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 )
最典型的应用就是gulp,
- 流程:
* 1. 读取文件
* 2. 创建压缩包
* 3. 将读取的数据流写入压缩包
* 4. 输出压缩包
- http :从某个api接口中,进行数据请求
- 主要有两种方式
http.get
http.request
- 主要有两种方式
const http = require( 'http' )
http.get('http://api.k780.com/?app=weather.city&cou=1&appkey=43880&sign=6a31f4fe1408d69bb0417b046eeae5b6&format=json', (res) => {
const { statusCode } = res; // 获取请求状态码 200 301 302 303 304 404 500
const contentType = res.headers['content-type']; // 获取请求类型数据类型
// json数据的content-type 'content-type': 'application/json'
let error;
if (statusCode !== 200) { // 如果状态码不是200 ,输出报错信息
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) { // 如果报错了,将报错信息存入日志
console.error(error.message);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8'); // 字符编码
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; }); // 通过data事件拼接数据流
res.on('end', () => { // 获取数据结束了
try { // 高级编程语法 捕获错误信息
console.log( rawData );
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
第三方模块: 我们一般都是从npmjs.com这个网站拉取
使用流程:
1. 安装
先创建package.json 文件
npm/cnpm i request -S/-D
-S --save 生产环境
-D --save-dev dev development的简写 开发环境
2. 使用
request这个模块是做数据请求
3. Node中数据请求存在跨域吗?
- 不存在
- 后端服务器有两种类型
- web服务器 【 静态服务器 】
- api服务器 【 暴露接口 】
- 请求头部报文
- general 请求基本信息
- response Headers 响应头
- request Headers 请求头
- 携带参数
- query string paramters get请求
- form data post 请求
const http = require( 'http' )
const host = 'localhost'
const port = 8000
http.createServer(( request,response ) => {
// response.writeHead( 状态码,请求头 )
response.writeHead( 200, {
'Content-type': 'text/html;charset=utf8'
})
response.write('<h3> 这里使用Node创建的一个静态服务器 </h3>') // 往前端发送信息
response.end() // 告诉前端信息已经结束了
}).listen( port,host,() => {
console.log( `The server is running at: http://${ host }:${ port }` )
})
Node.js中event模块
Node.js中 事件的发布 + 事件的订阅 表示一个任务的执行
const Events = require(‘events’)
const fs = require( ‘fs’ )
const http = require( ‘http’ )
const host = ‘localhost’
const port = 3000
class myEvent extends Events{}
类的继承
const myevent = new myEvent()
实例化类得到一个实例
console.log( myevent )
事件的发布
myevent.on(事件名称,事件的回调函数)
myevent.on(‘aa’,function () {
书写任务
任务: 将yyb.txt中的内容发送前台
http.createServer( ( req,res ) => {
res.writeHead( 200,{
‘Content-Type’: ‘text/html;charset=utf8’
})
1
fs.readFile(’./yyb.txt’,‘utf8’,( error,docs ) => { // error作为第一个参数的回调函数,我们叫做错误优先的回调函数
res.write(<h3> ${ docs } </h3>
)
res.end()
})
2
why? 错误?
res.end()
}).listen( port,host,() => {
console.log( 服务器运行在: http://${ host }:${ port }
)
})
})
事件的订阅
myevent.emit(事件名称)
myevent.emit( ‘aa’ )
后端
api服务器
Node.js中api服务器的创建,我们使用一个第三方库 express
后端解决跨域问题:
1. 设置请求头
2. 使用中间件
第三方的包 cors
const app = express() // 得到一个app对象
const port = 3000
const host = 'localhost'
const cors = require( 'cors' )
// 创建接口
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 200
}))
app.get( '/user', ( req,res,next ) => { // 回调函数我们称之为: 中间件 具有特定功能的一个函数
res.json({
id: 1,
name: 'wangwu',
class: '1'
})
})
app.get( '/demo', ( req,res,next ) => { // 回调函数我们称之为: 中间件 具有特定功能的一个函数
res.json({
id: 2,
name: 'zhangshan',
class: '2'
})
})
// 创建api服务器,并监听这个服务器
app.listen( port,host,() => {
console.log( `The server is running at : http://${ host }:${ port }` )
})
express
解决跨域问题
/*
反向代理的基本原理
我们的后端帮助我们请求数据 , 在将数据发送给我们自己前端
任务:
1. 后端请求数据
2. 将数据发送给前端 api服务器 express
const request = require( ‘request’ )
const express = require( 'express' )
const host = 'localhost'
const port = 3000
const app = express()
const url = '其他网站.json接口'
//创建接口
app.get('/position', ( req,res,next ) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // 设置请求头跨域
// 数据请求
request( url, ( error,response,body ) => {
res.json( JSON.parse( body ) )
})
})
解决跨域问题