本文介绍了流文件在节点/快递到客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将内容流式传输到可能存储在数据库中的客户端,它们将作为文件保存。



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



我看了一下res.download impl,它只是设置Content-Disposition头,然后是sendfile。



所以我可以使用这个帖子作为指导。



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



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

解决方案

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

一个基本的文件流看起来像这样。

  function(req, res,next){
if(req.url ===somethingorAnother){
res.setHeader(content-type,some / type);
fs.createReadStream(./ toSomeFile)。pipe(res);
} else {
next(); //不是我们的关心,传递给下一个中间件功能
}
}

这将负责绑定到数据结束事件。


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.

解决方案

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.

这篇关于流文件在节点/快递到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:51