節點v.4.2.3和貓鼬v.4.3.6Mongoose QueryStream.pause()不暫停?
我必須迭代一個大型(> 10k文檔)集合,並處理每個文檔。
閱讀關於如何處理這種迭代的文檔,我偶然發現了QueryStream,我認爲這會解決我所有的問題。
function progress(total, t, current) {
process.stdout.clearLine(); // clear current text
process.stdout.write(Math.round(t/total * 100) + '% ' + t + '/' + total + ' ' + current);
process.stdout.cursorTo(0);
}
function loadBalance(current, stream) {
if(!stream.paused && current > 50) {
log('DEBUG', 'loadBalance', 'pause');
stream.pause();
} else if (stream.paused && current < 10) {
log('DEBUG', 'loadBalance', 'resume');
stream.resume();
}
}
var total = 0,
error = 0,
goods = 0,
current = 0;
stream = Raw.find().stream();
stream.on('data', function (doc) {
heavyProcess(doc, function (err, refined) {
current = current + 1;
loadBalance(current, stream);
printP(total, goods + error, current);
if(err) {
error = error + 1;
current = current - 1;
loadBalance(current, stream);
} else {
new Pure(refined).save(function (err) {
if(err) {
error = error + 1;
current = current - 1;
loadBalance(current, stream);
} else {
goods = goods + 1;
current = current - 1;
loadBalance(current, stream);
}
});
}
});
}).on('error', function (err) {
log('ERROR', 'stream', err);
}).on('close', function() {
log('INFO', 'end', goods + '/' + total + ' (' + (goods/total*100) + '%) OK_');
log('INFO', 'end', error + '/' + total + ' (' + (error/total*100) + '%) NOK');
log('INFO', 'end', (total - goods - error) + ' missing');
});
LOADBALANCE不會被調用,並打印在暫停流,但'data'
事件繼續被解僱,甚至想過stream.paused
返回true。
我誤解了pause()
是做什麼的?還是我濫用QueryStream?