[英]nodejs stream readable stuck at first readable object
I have a NodeJS stream.Readable : 我有一个NodeJS流。可读 :
var async = require('async'),
util = require('util'),
ReadableStream = require('readable-stream').Readable;
function ArticleReader() {
ReadableStream.call(this, { objectMode: true });
}
util.inherits(ArticleReader, ReadableStream);
ArticleReader.prototype._read = function() {
var articles = ['article1', 'article2'];
var self = this;
async.each(articles, function(link, callback) {
self.push(article);
callback();
}, function(err) {
if (err) {
self.emit('error', err);
} else {
self.push(null);
}
});
};
And this is the consumer: 这是消费者:
var article = new ArticleReader();
article.on('readable', function() {
var buf = article.read();
console.log(buf);
});
article.on('end', function() {
console.log('end');
});
Here's the output: 这是输出:
'article1'
The problem is program is stuck at 'article1'
, it never reads 'article2'
, and it never reaches end
event too. 问题是程序停留在
'article1'
,它从不读'article2'
,它也永远不会到达end
事件。
Note that the event end
fires when there will be no more data to read. 请注意,当没有更多数据要读取时,事件
end
触发。
Also the end
event will not fire unless the data is completely consumed. 除非数据被完全消耗,否则不会触发
end
事件。 This can be done by switching into flowing mode
, or by calling read()
repeatedly until you get to the end. 这可以通过切换到
flowing mode
,或通过重复调用read()
直到结束来完成。
The solution, was to keep reading until the end of the stream is reached. 解决方案是继续阅读直到达到流的末尾。
var readable = getReadableStreamSomehow();
readable.on('readable', function() {
while ((buf = readable.read()) != null) {
console.log(buf);
}
}
readable.on('data', function(chunk) {
console.log('got %d bytes of data', chunk.length);
})
readable.on('end', function() {
console.log('there will be no more data.');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.