如何在节点中使用读取流发送多个文件? [英] How to send multiple files with a read stream in node?

查看:38
本文介绍了如何在节点中使用读取流发送多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含两个文件的目录,并且我想发送两个文件.假设和 index.html 和 style.css.

If I have a directory with two files and I want to send send both of them. Hypothetically and index.html and style.css.

Router.get('/', function(req, res) {
  var indexStream = fs.createWriteStream('path to index')
  var cssStream = fs.createWriteStream('path to style')

  indexStream.pipe(res)
  styleStream.pipe(res)

})

据我所知 .pipe(res) 隐式调用 res.end() 以便我可以发送到单独的读取流.感谢您的帮助~

As I understand .pipe(res) implicitly calls res.end() so I can send to separate read streams. Thanks for any help~

推荐答案

你不要这样做.

这不是 Node.js 的限制.这是您的 Web 浏览器的限制(或者更确切地说,是 HTTP 的限制).您要做的是分别发送每个文件:

It's not a limitation of Node.js. It's a limitation of your web browser (or rather, a limitation of HTTP). What you do instead is send each file separately:

Router.get('/', function(req, res) {
  res.sendFile('path to index')
})
Router.get('/style.css', function(req, res) {
  res.sendFile('path to style')
})

或者,如果您的路由器支持它,您可以使用静态中间件来为您的 css 文件提供服务.

Alternatively if your router supports it you can use a static middleware to serve your css files.

是的,也不是.

如果您的浏览器支持,节点 http.Server 支持 keep-alive.这意味着它会在可能的情况下重新使用已经打开的连接.因此,如果您担心延迟并希望实现持久连接,那么它已经为您解决了.

If your browser supports it, node http.Server supports keep-alive. That means it will re-use an already opened connection if possible. So if you're worried about latency and want to implement persistent connections then it's already taken cared of for you.

如果你愿意,你可以通过设置 server.timeout 来改变 keep-alive 超时,但我认为 2 分钟的默认值对于大多数网络来说已经足够了页.

If you want, you can change the keep-alive timeout by setting server.timeout but I think the default value of 2 minutes is more than enough for most web pages.

这篇关于如何在节点中使用读取流发送多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆