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 get okkk
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?
To consume a readable stream, we can use the pipe / unpipe methods, or the read / unshift / resume methods. To consume a writable stream, we can make it the destination of pipe / unpipe , or just write to it with the write method and call the end method when we're done.
It is unmaintained Express has not been updated for years, and its next version has been in alpha for 6 years. People may think it is not updated because the API is stable and does not need change. The reality is: Express does not know how to handle async/await .
pipe() method is used to attach a readable stream to the writable Stream. Stream. pipe() method is also used in file streams in NodeJs. Stream. pipe() can be used for HTTP requests and response objects.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With