Nodejs: How to send a readable stream to the browser

橙三吉。 提交于 2019-12-12 17:24:25

问题


If I query the box REST API and get back a readable stream, what is the best way to handle it? How do you send it to the browser?? (DISCLAIMER: I'm new to streams and buffers, so some of this code is pretty theoretical)

Can you pass the readStream in the response and let the browser handle it? Or do you have to stream the chunks into a buffer and then send the buffer??

export function getFileStream(req, res) {
  const fileId = req.params.fileId;
  console.log('fileId', fileId);
  req.sdk.files.getReadStream(fileId, null, (err, stream) => {
    if (err) {
      console.log('error', err);
      return res.status(500).send(err);
    }
    res.type('application/octet-stream');
    console.log('stream', stream);
    return res.status(200).send(stream);
  });
}

Will ^^ work, or do you need to do something like:

export function downloadFile(req, res) {
  const fileId = req.params.fileId;
  console.log('fileId', fileId);
  req.sdk.files.getReadStream(fileId, null, (err, stream) => {
    if (err) {
      console.log('error', err);
      return res.status(500).send(err);
    }
    const buffers = [];
    const document = new Buffer();
    console.log('stream', stream);
    stream.on('data', (chunk) => {
      buffers.push(buffer);
    })
    .on('end', function(){
      const finalBuffer = Buffer.concat(buffers);
      return res.status(200).send(finalBuffer);
    });
  });
}

回答1:


The first example would work if you changed you theoretical line to:

- return res.status(200).send(stream);
+ res.writeHead(200, {header: here})
+ stream.pipe(res);

That's the nicest thing about node stream. The other case would (in essence) work too, but it would accumulate lots of unnecessary memory.

If you'd like to check a working example, here's one I wrote based on scramjet, express and browserify:

https://github.com/MichalCz/scramjet/blob/master/samples/browser/browser.js

Where your streams go from the server to the browser. With minor mods it'll fit your problem.



来源:https://stackoverflow.com/questions/40387566/nodejs-how-to-send-a-readable-stream-to-the-browser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!