Reputation: 104
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)
})
As I understand .pipe(res)
implicitly calls res.end() so I can send to separate read streams. Thanks for any help~
Upvotes: 3
Views: 3505
Reputation: 113886
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.
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.
Upvotes: 1
Reputation: 106696
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');
});
Upvotes: 0