expressjs - piping to response stream doesn't work
17,602
Solution 1
It worked when I replaced req.pipe(str).pipe(res)
with req.pipe(through(write, end)).pipe(res)
which essentially makes sure that a new instance of through stream is created for every request.
Solution 2
I had this same problem and looks like res
was not being finished properly. So I added a callback to my stream and ended que res
myself. That fixed my problem:
stream.on('end', () => res.end());
stream.pipe(res);
Comments
-
Jatin over 1 year
I have this basic express app:
var express = require('express'); var app = express(); var PORT = 3000; var through = require('through'); function write(buf) { console.log('writing...'); this.queue('okkkk'); } function end() { this.queue(null); } var str = through(write, end); /* routes */ app.get('/', function(req, res){ res.send("Hello!"); }) app.post('/stream', function(req, res){ var s = req.pipe(str).pipe(res); s.on('finish', function() { console.log('all writes are now complete.'); // printed the first time }); }); /* listen */ app.listen(PORT, function () { console.log('listening on port ' + PORT + '...'); });
When I post some data to
/stream
endpoint for the first time after starting the server I getokkk
as the response which is what I expect. However, after that, any requests to/stream
endpoint just timeout and not return any response.Why is it so? What's exactly happening here?