这次包含一个读流对象,一个写流对象。
全部代码
/** * 用流来实现斐波那契数列 * * @author yyy */ var stream=require('stream'); var util=require('util'); // -------------- 下面是可读流 ----------------- function StreamChildRead(n) { this.a=0; this.b=1; this.n = n; stream.Readable.call(this); } util.inherits(StreamChildRead, stream.Readable ); // 覆盖父类的方法 StreamChildRead.prototype._read = function(){ this.push( this.a.toString()); this.push( this.b.toString()); for(let i=2;i<= this.n+1-2;i++) { [this.a, this.b] = [this.b, this.a+this.b]; this.push( `${this.b}` ); } this.push(null); }; // --------------- 下面是可写流 -------------- function StreamChildWrite() { this.count=0; stream.Writable.call(this); } util.inherits(StreamChildWrite, stream.Writable ); // 覆盖父类的方法 StreamChildWrite.prototype._write = function(chunk,encoding,callback){ process.stdout.write( ('f('+ this.count++) +"):"+ chunk.toString()+'\n'); callback(); }; (new StreamChildRead(10)).pipe(new StreamChildWrite());
输出如下所示:
f(0):0 f(1):1 f(2):1 f(3):2 f(4):3 f(5):5 f(6):8 f(7):13 f(8):21 f(9):34