Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressjs - piping to response stream doesn't work

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?

like image 523
Jatin Avatar asked Mar 02 '15 20:03

Jatin


People also ask

How do you pipe a readable stream?

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.

Is Express JS unmaintained?

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 .

What is piping in streams node JS?

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.


1 Answers

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);
like image 78
Sergio Avatar answered Nov 06 '22 11:11

Sergio