将 node/express 中的文件流式传输到客户端

将 node/express 中的文件流式传输到客户端

问题描述:

我想将内容流式传输给客户端,这些内容可能存储在 db 中,他们会将其另存为文件.

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

显然 res.download 可以很好地完成这项工作,但没有任何响应.* 函数接受流,只接受文件路径.

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

我查看了 res.download impl,它只设置了 Content-Disposition 标头,然后设置了一个发送文件.

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

所以我可以使用这篇文章作为指导来实现这一点.Node.js:到响应的管道流通过 HTTPS 冻结

So I could achieve this using this post as a guide. Node.js: pipe stream to response freezes over HTTPS

但似乎我会错过 res.send 执行的所有包装方面.

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?

目前正在创建临时文件,所以我现在只能使用 res.download.

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

您可以直接流式传输到响应对象(它是一个 Stream).

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

这将负责绑定到 dataend 事件.

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