第一个Stream例子
const fs = require('fs')
const stream = fs.createWriteStream('./big_file.txt')
for(let i=0;i<10000;i++)[
stream.write(`这是第${i}行内容,我们需要很多很多内容,要不停地写文件啊啊啊啊啊啊回车\n`)
}
stream.end()//别忘了关掉 stream
console.log('done')
分析
打开流,多次往里面塞内容,关闭流
看起来就是可以多次写嘛,没什么大不了的
最终我们得到一个128兆左右的文件
Stream流
![](https://img.haomeiwen.com/i16572102/f9e6da7c9f79365d.png)
释义
stream
是水流,但默认没有水
stream.write
可以让水流中有水(数据)
每次写的小数据叫做chunk
(块)
产生数据的一段叫做source
(源头)
得到数据的一段叫做sink
(水池)
第二个例子
const http = require("http");
const fs = require("fs");
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)
分析
用任务管理器看Node.js,内存占用,大概130Mb;
第三个例子
const http = require('http')
const fs = require('fs')
const server = http.createServer()
server.on('request', (request, response) => {
const stream = fs.createReadStream('./big_file.txt')
stream.pipe(response)
})
server.listen(8888)
** 分析**
- 查看 Node.is 内存占用,基本不会高于30 Mb
- 文件 stream 和 response stream 通过管道相连
管道
![](https://img.haomeiwen.com/i16572102/1faa0770aa1481cf.png)
释义
两个流可以用一个管道相连
stream1的末尾连接上stream2的开端只要stream1有数据,就会流到stream2
常用代码
stream1.pipe(stream2)
链式操作
a.pipe(b).pipe(c)
//等价于
a.pipe(b)
b.pipe(c)
管道续
管道可以通过事件实现
// stream1 一有数据就塞给
stream2stream1.on('data', (chunk) => {
stream2.write(chunk)
})
// stream1 停了,就停掉
stream2stream1.on('end', () => {
stream2.end()
})
网友评论