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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13106096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:33:18  来源:igfitidea点击:

Stream files in node/express to client

node.jsexpress

提问by Tim

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

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

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

显然 res.download 可以很好地完成这项工作,但没有一个 response.* 函数接受流,只接受文件路径。

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

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

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

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

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

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

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.

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

回答by Morgan ARR Allen

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

您可以直接流式传输到响应对象(它是一个 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 dataand endevents.

这将负责绑定到dataend事件。

回答by sasidhar79

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

确保来自客户端的 AJAX 请求设置了适当的“responseType”。例如像

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