node中的Readable - flowing/non-flowing mode

大家都知道在node中Readable Stream有两种模式: flowing modenon-flowing mode

对于flowing modeReadable Stream, 我们是没法控制它何时去读数据读多少的,它会去尽快的去消耗data,并emit出来。

1 // in lib/_stream_readable.js
2 if (state.flowing && state.length === 0 &&!state.sync) {  
3         stream.emit('data', chunk);
4         stream.read(0);

 

non-flowing mode的Readable Stream, 则不会主动的去读数据,需要自己显示的去调用read方法才能得到数据。

1 // in lib/_stream_readable.js
2 // update the buffer info.
3 state.length += state.objectMode ? 1 : chunk.length;  
4 if (addToFront)  
5   state.buffer.unshift(chunk);
6 else  
7   state.buffer.push(chunk);

 

可以看到当有数据时,只是将数据放入buffer中,而不是直接emit。

所以如果想控制stream的读取顺序,大小和时间,应该使用non-flowing mode,而当使用pipe有下游管道对数据进行处理时,这个时候数据的读取和处理应该交给下游管道处理,应该尽可能快的提供数据,所以要使用flowing mode。而这也是node会在attach 'data'事件之后,自动转变为flowing mode的原因,避免错误的使用或者忘记切换模式。

而pipe时则会注册data事件,所以使用了pipe也会转换为flowing mode

1 var src = this;  
2 ...
3 src.on('data', ondata);

 

link: http://villadora.me/2014/07/24/nodezhong-de-readable-flowingnon-flowing-mode/index.html

posted on 2014-08-01 22:04  dvilla  阅读(482)  评论(0编辑  收藏  举报

导航