node的流对象学习(读流,斐波那契数列实现)

学习node的流对象,拿一个数列练手。

全部代码如下:


/**
* 用流来实现斐波那契数列
*
* @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);


也可以正确执行,请读者推测输出有什么不同。

读流和写流可以管道串联起来执行,可参见
[url=http://xieye.iteye.com/blog/2400367]读流和写流学习[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值