Stream files in node/express to client

node.jsExpress

node.js Problem Overview


I want to stream content to clients which is possibly stored in db, which they would save as files.

Obviously res.download would do the job nicely, but none of the response.* functions accept a stream, only file paths.

I had a look at res.download impl and it just sets Content-Disposition header and then a sendfile.

So I could achieve this using this post as a guide. https://stackoverflow.com/questions/8257544/node-js-pipe-stream-to-response-freezes-over-https

But it seems I would miss out on all the wrapping aspects that res.send performs.

Am I missing something here or should I just do the pipe and not worry about it - what is best practice here?

Currently creating temp files so I can just use res.download for now.

node.js Solutions


Solution 1 - node.js

You can stream directly to the response object (it is a Stream).

A basic file stream would look something like this.

function(req, res, next) {
  if(req.url==="somethingorAnother") {
    res.setHeader("content-type", "some/type");
    fs.createReadStream("./toSomeFile").pipe(res);
  } else {
    next(); // not our concern, pass along to next middleware function
  }
}

This will take care of binding to data and end events.

Solution 2 - node.js

Make sure that your AJAX request from the client has an appropriate 'responseType' set. for example like

$http({
  method :'GET',
  url : http://url,
  params:{},
  responseType: 'arraybuffer'
}).success()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimView Question on Stackoverflow
Solution 1 - node.jsMorgan ARR AllenView Answer on Stackoverflow
Solution 2 - node.jssasidhar79View Answer on Stackoverflow