关于 node stream 生命周期的问题

2016-05-15 16:32:18 +08:00
 ssehacker

对 stream 的一些问题感到迷惑,还是直接上代码吧:

let fs = require('fs');

const Readable = require('stream').Readable;
const util = require('util');

util.inherits(MyReadable, Readable);
function MyReadable(source,options){
	Readable.call(this, options);	
	this._source = source;


	 source.on('readable', () => {
	 	//注释下面这行
	    this.read(0); //FLAG
	 });

}

var b = true;
MyReadable.prototype._read = function(){
	let chunk = this._source.read();
	if(b){
		if(!chunk){
			return this.push('');
		}else{
			b=false;
		}
	}
	if(chunk){
		 this.push(chunk);
	}else{
		this.push(null);
	}
}

//case1
function getStream(){
	var rs = new Readable();
	rs.push('abcdefg');
	rs.push(null);
	return rs;
}
//case2
function getStream2(){
	//hello.txt 是包含“ abcdefg ”字符串的文本文件。
	return fs.createReadStream('./hello.txt', {encoding: null});	
}

var rs = getStream2();

let myrs = new MyReadable(rs);


myrs.pipe(process.stdout);

上面这段代码输出: abcdefg 。 问题一: 如果我把下面这行注释

this.read(0);

则没有任何输出,为什么? 如果改成:

this.read();

好像效果和 this.read(0)一样。

问题二: 如果把 var rs = getStream2(); 改成 var rs = getStream(); 则 FLAG 那行不注释也能有输出,这又是为什么?

求大神赐教。谢谢。

在线等啊。。。

2721 次点击
所在节点    Node.js
3 条回复
ssehacker
2016-05-15 16:34:27 +08:00
有人吗?
weaponX
2016-05-16 10:06:41 +08:00
最近我也在学习这部分,发点资料给你参考,我看了几遍还是不清楚
可以多交流。。。
http://fe.meituan.com/stream-basics.html
des
2016-05-16 14:38:56 +08:00
标准的流是有缓存的,一般都是行缓存
你把 push('abcdefg'); 改成 push('abcdefg\n');应该就能输出了,如果我没猜错的话。
当然你也可以手动 flush 一下

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/278782

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX