Jatin
Jatin

Reputation: 14269

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?

Upvotes: 7

Views: 22588

Answers (2)

Sergio
Sergio

Reputation: 28837

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);

Upvotes: 13

Jatin
Jatin

Reputation: 14269

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.

Upvotes: 7

Related Questions