IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    关于node stream的生命周期

    ssehacker发表于 2016-05-15 08:05:53
    love 0

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

    求大神赐教。谢谢。



沪ICP备19023445号-2号
友情链接