N-ZOO / issue-record

组内技术点沉淀区
4 stars 0 forks source link

流(Stream) #5

Open coxo opened 8 years ago

coxo commented 8 years ago

流(Stream)是可读,可写或双工的。

可以通过require('stream')加载流的基类,其中包括四类流,

另外如果觉得上述四类基类流不能满足需求,可以编写自己的扩充类流。 像我的BearStream。

coxo commented 8 years ago
SimpleProtocol.prototype = Object.create(
 //SimpleProtocol继承readable类
  Readable.prototype, { constructor: { value: SimpleProtocol }}
);
daxiongjun commented 8 years ago

补充个板栗

自定义readable stream的实现

var Stream = require('stream');
var Read = Stream.Readable;
var util = require('util');

util.inherits(MyReadStream, Read);

function MyReadStream(data, opt) {
    Read.call(this, opt);
    this.data = data || [];
}
MyReadStream.prototype._read = function () {
    var _this = this;
    this.data.forEach(function (d) {
        _this.push(d);
    })
    this.push(null);
}

var data = ['aa', 'bb', 'cc'];
var r = new MyReadStream(data);

r.on('data', function (chunk) {
    console.log(chunk.toString());
})
VaJoy commented 8 years ago

@daxiongjun 大熊去学markdown怎么用