简体   繁体   English

在Node.js中合并流

[英]Merging streams in nodejs

I'm working with MongoDB's cursor streaming functionality. 我正在使用MongoDB的游标流功能。 In my code multiple documents are joined together, so I want to denormalize the documents and then stream them to the client. 在我的代码中,多个文档连接在一起,因此我想对文档进行规范化,然后将其流式传输到客户端。 I am confused on where to even start. 我对从哪里开始感到困惑。 Here is some pseudo-code of what I have tried: 这是我尝试过的一些伪代码:

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;

I get some errors because it does not implement _read . 我收到一些错误,因为它没有实现_read This method also makes it trickier to find when to call stream.push(null) . 此方法还使查找何时调用stream.push(null)变得更加棘手。

What is the solution to this problem? 这个问题有什么解决方案?

The _read method is necessary to implement a readable stream. _read方法对于实现可读流是必需的。 If you prefer a simpler interface, you'll probably prefer to use a PassThrough stream: 如果您希望使用更简单的界面,则可能更喜欢使用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;

Using a readable stream can be useful if you intend to take care of back pressure but i'm not sure the mongodb API provides such mechanism anyway. 如果您打算解决背压问题,那么使用可读流可能会很有用,但是我不确定mongodb API是否会提供这种机制。

Also, look at the mongodb API to see how to properly check for the collection entries stream end and call the stream.end() method accordingly. 另外,请查看mongodb API,以了解如何正确检查集合条目流的结尾并相应地调用stream.end()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM