Stream模块是Node.js一个重要模块。数据流是可读、可写或即可读又可写得内存结构。接下来介绍使用Stream模块来创建流,以及从它们中读出数据和向它们写入数据。
1 Readable流
Readable流可以方便地读取从其他来源进入应用程序的数据。
Readable流公开了一些事件:
- readable:在数据块可以从流中读取时发出。
- data:类似于readable,但数据的处理程序被连接时,流被转换成流动的模式,并且数据处理程序被连续地调用,直到所有数据被用尽。
- end:当数据不再被提供时由流发出。
- close:当底层的资源,如文件,关闭时发出。
- error:出错时发出。
示例:
var stream = require('stream');
var util = require('util');
util.inherits(Output, stream.Readable);
function Output() {
stream.Readable.call(this);
this.content = ['开始数据', '中间数据', '结束数据'];
this._index = 0;
}
Output.prototype._read = function () {
if (this._index > this.content.length) {
this.push(null);
} else {
this.push(this.content[this._index]);
this._index ++;