为什么需要stream
- 不用stream的情况:太耗内存
const fs = require('fs')
const http = require('http')
const server = http.createServer()
server.on('request',(request,response)=>{
fs.readFile('./big_file.txt',(error,data)=>{
if(error)throw error
response.end(data)
console.log('done')
})
})
server.listen(8888)
- 优化:用
pipe
连接读文件流
和http可写流
:
image.png
const fs = require('fs')
const http = require('http')
const server = http.createServer()
server.on('request',(request,response)=>{
const stream = fs.createReadStream('./big_file.txt')
stream.pipe(response)
stream.on('end',()=>console.log('done'))
})
server.listen(8888)
-
管道等同于以下事件:
image.png -
stream其实是个事件,可读流有
data,end
等事件,data事件回调参数chunk
是二进制buffer
,如果想要转译的话,用toString()
const fs = require('fs')
const http = require('http')
const server = http.createServer()
server.on('request',(request,response)=>{
const stream = fs.createReadStream('./big_file.txt')
stream.on('data',(chunk)=>{
console.log('读取了一次数据')
console.log(chunk.toString())
})
stream.on('end',()=>{
console.log('全部读取完了')
})
})
server.listen(8888)
stream分类:
- Readable:可读
- Writable:可写
- Duplex:可读可写(双向)
- Transform:可读可写(变化),例如babel,scss转译等
Readable Stream:
- 静止态paused和流动态flowing
- 默认处于paused
- 添加data事件监听,就变成flowing
- 删掉data事件监听,就变成paused
- pause()可以将它变为paused
- resume()可以将它变为flowing
Writable Stream:
- drain事件:
调用stream.write(chunk)可能会得到false,表示数据积压了,这时就不能再write了,要监听drain事件,等drain事件触发了即数据不积压了,才能继续write
网友评论