Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
428 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...