node.js中如何实现并使用可读流与可写流在stream流中?
- 内容介绍
- 文章标签
- 相关推荐
本文共计2853个文字,预计阅读时间需要12分钟。
本文示例讲解了Node.js中Stream流中可读流和可写流的实现与应用方法。分享给广大读者,以便参考学习。
Node.js中的Stream是处理流式数据的一种抽象接口,可以高效地处理大量数据。它包括三种类型的流:可读流、可写流和可读可写流。
1. 可读流(Readable Stream)
可读流负责数据的读取,它具有以下方法:
- `readable.read(size)`:读取数据到缓存区,并返回一个Buffer。- `readable.on('data', callback)`:当有数据可读时,触发该事件,并执行回调函数。- `readable.on('end', callback)`:当流数据读取完毕时,触发该事件。
示例:
javascriptconst { Readable }=require('stream');
const readable=new Readable({ read() { this.push('Hello'); this.push(' '); this.push('World'); this.push(null); // 结束流 }});
readable.on('data', (chunk)=> { process.stdout.write(chunk);});
2. 可写流(Writable Stream)
可写流负责数据的写入,它具有以下方法:
- `writable.write(chunk, encoding, callback)`:将数据写入流,并可选地指定编码,当数据写入完成时,执行回调函数。
本文共计2853个文字,预计阅读时间需要12分钟。
本文示例讲解了Node.js中Stream流中可读流和可写流的实现与应用方法。分享给广大读者,以便参考学习。
Node.js中的Stream是处理流式数据的一种抽象接口,可以高效地处理大量数据。它包括三种类型的流:可读流、可写流和可读可写流。
1. 可读流(Readable Stream)
可读流负责数据的读取,它具有以下方法:
- `readable.read(size)`:读取数据到缓存区,并返回一个Buffer。- `readable.on('data', callback)`:当有数据可读时,触发该事件,并执行回调函数。- `readable.on('end', callback)`:当流数据读取完毕时,触发该事件。
示例:
javascriptconst { Readable }=require('stream');
const readable=new Readable({ read() { this.push('Hello'); this.push(' '); this.push('World'); this.push(null); // 结束流 }});
readable.on('data', (chunk)=> { process.stdout.write(chunk);});
2. 可写流(Writable Stream)
可写流负责数据的写入,它具有以下方法:
- `writable.write(chunk, encoding, callback)`:将数据写入流,并可选地指定编码,当数据写入完成时,执行回调函数。

