全部代码如下:
/** * 用流来实现斐波那契数列 * * @author yyy */ var stream=require('stream'); var util=require('util'); // 构造方法 // n是最大个数 function StreamChild(n) { this.a=0; this.b=1; this.n = n; stream.Readable.call(this); } util.inherits(StreamChild, stream.Readable ); // 覆盖父类的方法 StreamChild.prototype._read = function(){ this.push('f(0):'+ this.a.toString()); this.push('f(1):'+ 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( `f(${i}):${this.b}` ); } this.push(null); }; var child=new StreamChild(10); // 下面设置监听器,注意:同时也开始执行读事件!这也是流对象的特点! child.on('data',(data)=>{ console.log(data.toString()); }); child.on('end',()=>{ console.log('end'); });
下面是输出结果:
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 end
说明,还有第2种写法
把最后的on(‘data’)和on('end')语句去除,用一句话代替。
child.pipe(process.stdout);
也可以正确执行,请读者推测输出有什么不同。
读流和写流可以管道串联起来执行,可参见
读流和写流学习