node的流对象学习(读流和写流)

依然用上次的数列实现。

这次包含一个读流对象,一个写流对象。
全部代码


/**
* 用流来实现斐波那契数列
*
* @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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值