Skip to content Skip to sidebar Skip to footer

How To Send Multiple Files With A Read Stream In Node?

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

Solution 1:

You don't do this.

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

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


Doesn't this create lots of connections?

Yes, and no.

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.

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.

Solution 2:

Typically you'd serve your html from a route handler and have all static assets automatically handled by the express.static() middleware.

You can also use res.sendFile() to simplify things even further.

So you could have something like:

// 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');
});

Post a Comment for "How To Send Multiple Files With A Read Stream In Node?"