简体   繁体   English

用管道将oboe.js解析为json到Node.js中的http响应对象

[英]Piping oboe.js parsed json to http response object in Node.js

I'm using Oboe.js to parse JSON from a Node readStream and I want to send this back to the client requesting it in a memory-efficient manner. 我正在使用Oboe.js来从Node readStream解析JSON,我想将其发送回客户端以节省内存的方式请求它。 Is it possible to pipe data from Oboe's node or path events to a Node.js HTTP response object, so I can delivered parsed data on the fly to a client rather than collecting it in full and sending it all at once? 是否可以将数据从Oboe的nodepath事件传递到Node.js HTTP响应对象,以便我可以将已解析的数据即时传递给客户端,而不是全部收集并立即发送? This is the code I have so far: 这是我到目前为止的代码:

const express = require('express');
const app = express();
const PORT = 3000;
const oboe = require('oboe');
const fs = require('fs');

app.get('/download', (req, res) => {

    const jsonDataStream = fs.createReadStream('./citylots.json');

    oboe(jsonDataStream)
        .node('features.*', function(feature) {
           // res.send is non-streaming. how to stream?
            res.send(feature);
        });
});

app.listen(PORT, () => console.log(`up on port ${ PORT }!`));

For your specific question, I think the problem has to do with the fact that res.send terminates the response ( docs ). 对于您的特定问题,我认为问题与res.send终止响应( docs )有关。 Given that res is a writable stream, you can call res.write to write a string to the response. 鉴于res是可写流,您可以调用res.write将字符串写入响应。 You will have to do some additional work to insert commas as well as a starting [ and ] . 您将需要做一些额外的工作来插入逗号以及开始的[]

const express = require('express');
const app = express();
const PORT = 3000;
const oboe = require('oboe');
const fs = require('fs');

app.get('/download', (req, res) => {

    const jsonDataStream = fs.createReadStream('./citylots.json');

    oboe(jsonDataStream)
        .node('features.*', function(feature) {
          res.write(JSON.stringify(feature));
        });
});

app.listen(PORT, () => console.log(`up on port ${ PORT }!`));

To step back from this though, I want to be sure Oboe is good for your use case. 但是要退一步,我想确保Oboe适合您的用例。 It might be complicating your implementation without much benefit. 这可能会使您的实现复杂化,而没有太多好处。 Is your goal to reduce memory by sending less data to the client? 您的目标是通过减少向客户端发送数据来减少内存吗? In other words, are you trying to avoid sending all of citylots.json and instead want to only send its features ? 换句话说,您是否要避免发送所有citylots.json ,而只希望发送其features

I think what you need is keeping sending data without holding the entire file in memory. 我认为您需要的是继续发送数据而不将整个文件保存在内存中。

Therefore, you need to use pipe. 因此,您需要使用管道。 Pipe will allow you to send the data with chunks 管道将使您可以分块发送数据

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

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