[英]Merging streams in nodejs
我正在使用MongoDB的游標流功能。 在我的代碼中,多個文檔連接在一起,因此我想對文檔進行規范化,然后將其流式傳輸到客戶端。 我對從哪里開始感到困惑。 這是我嘗試過的一些偽代碼:
var stream = new Readable({ objectMode: true });
var cursor = collection.find();
cursor.forEach(fetch);
function fetch(document) {
stream.push(document);
// Get all joined documents and run fetch() on them
}
return stream;
我收到一些錯誤,因為它沒有實現_read
。 此方法還使查找何時調用stream.push(null)
變得更加棘手。
這個問題有什么解決方案?
_read方法對於實現可讀流是必需的。 如果您希望使用更簡單的界面,則可能更喜歡使用PassThrough流:
var stream = new PassThrough({ objectMode: true });
var cursor = collection.find();
cursor.forEach(fetch);
function fetch(document) {
stream.write(document);
// Get all joined documents and run fetch() on them
}
return stream;
如果您打算解決背壓問題,那么使用可讀流可能會很有用,但是我不確定mongodb API是否會提供這種機制。
另外,請查看mongodb API,以了解如何正確檢查集合條目流的結尾並相應地調用stream.end()方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.