对 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 那行不注释也能有输出,这又是为什么?
求大神赐教。谢谢。
在线等啊。。。
1 ssehacker OP 有人吗? |
2 weaponX 2016-05-16 10:06:41 +08:00 |
![]() | 3 des 2016-05-16 14:38:56 +08:00 via Android 标准的流是有缓存的,一般都是行缓存 你把 push('abcdefg'); 改成 push('abcdefg\n');应该就能输出了,如果我没猜错的话。 当然你也可以手动 flush 一下 |