处理mongodb时直接stream式传输错误来表示响应

我只是开始使用mongodbstreamfunction来直接stream数据到快速响应 。

为此,我使用在这个问题上find的一段代码:

cursor.stream().pipe(JSONStream.stringify()).pipe(res); 

当游标返回MongoError时,我想用500状态标记响应。 不幸的是,在这个代码中,错误以200状态返回到JSON中。

我怎样才能使用简单的解决scheme来处理? 我是否必须在光标的错误事件中处理? 如果是这样,如果发生错误,我怎么能告诉不要直接stream式expression回应?

编辑

我已经尝试了一个解决scheme,像这样处理stream中的错误事件:

 var stream = cursor.stream(); stream.on('error', function(err){ res.status(500).send(err.message); }); stream.pipe(JSONStream.stringify()).pipe(res); 

不幸的是,当发生错误时,我得到了一个Error: write after end从快速Error: write after end因为我已经在错误事件中发送了响应。

当光标stream失败后,如何将标记为错误状态的响应?

当ReadStream结束或发生错误时,WriteStream结束。

所以你需要以某种方式防止在pipe道中发生错误时的这种默认行为。 您可以通过将{end: false}作为pipe道选项来传递。

这个选项改变了默认行为,所以即使发生错误,你的写入stream仍然是打开的,你可以继续发送更多的数据(例如错误状态)。

 var stream = cursor.stream(); stream.on('error', function () { res.status(500).send(err.message); }); stream.on('end', function(){ //Pipe does not end the stream automatically for you now //You have to end it manually res.end(); }); stream.pipe(res, {end:false}); //Prevent default behaviour 

有关更多信息,请访问:
https://nodejs.org/dist/latest-v6.x/docs/api/stream.html#stream_readable_pipe_destination_options