V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ssehacker
V2EX  ›  Node.js

关于 node stream 生命周期的问题

  •  1
     
  •   ssehacker · 2016-05-15 16:32:18 +08:00 · 2713 次点击
    这是一个创建于 2905 天前的主题,其中的信息可能已经有所发展或是发生改变。

    对 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 那行不注释也能有输出,这又是为什么?

    求大神赐教。谢谢。

    在线等啊。。。

    3 条回复    2016-05-16 14:38:56 +08:00
    ssehacker
        1
    ssehacker  
    OP
       2016-05-15 16:34:27 +08:00
    有人吗?
    weaponX
        2
    weaponX  
       2016-05-16 10:06:41 +08:00
    最近我也在学习这部分,发点资料给你参考,我看了几遍还是不清楚
    可以多交流。。。
    http://fe.meituan.com/stream-basics.html
    des
        3
    des  
       2016-05-16 14:38:56 +08:00 via Android
    标准的流是有缓存的,一般都是行缓存
    你把 push('abcdefg'); 改成 push('abcdefg\n');应该就能输出了,如果我没猜错的话。
    当然你也可以手动 flush 一下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4859 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:56 · PVG 17:56 · LAX 02:56 · JFK 05:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.