如何用节点中的读取stream发送多个文件?

如果我有一个目录有两个文件,我想发送它们两个。 假设和index.html和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(),所以我可以发送到单独的读取stream。 感谢您的帮助〜

你不这样做。

这不是Node.js的限制。 这是你的网页浏览器的一个限制(或者说HTTP的限制)。 你所做的是分别发送每个文件:

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

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


这不会创build大量的连接吗?

是的,没有。

如果您的浏览器支持,节点http.Server支持keep-alive 。 这意味着如果可能的话,它将重新使用已经打开的连接。 所以,如果你担心延迟,并希望实现持续的连接,那么它已经被照顾好了。

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

通常情况下,您将从路由处理程序提供html,并使所有静态资源由express.static()中间件自动处理。

你也可以使用res.sendFile()来进一步简化事情。

所以你可以有这样的东西:

 // Use whatever the correct path is that should be the root directory // for serving your js, css, and other static assets. app.use(express.static(path.join(__dirname, 'public'))); // ... Router.get('/', function(req, res) { res.sendFile('path to index'); });