floatdrop
floatdrop

Reputation: 612

Node async stream piping

I have this code working in Node 0.10, but it prints nothing in 0.8

var http = require('http');
var req = http.request('http://www.google.com:80', function(res) {
    setTimeout(function() {
        res.pipe(process.stdout);
    }, 0);
});
req.end();

After some guessing I found workaround:

var http = require('http');
var req = http.request('http://www.google.com:80', function(res) {
    res.pause();
    setTimeout(function() {
        res.resume();
        res.pipe(process.stdout);
    }, 0);
});
req.end();

But documentation says, that pause is advisory and this is confuses me. Why should I pause stream, which is not connected anywhere?

Upvotes: 4

Views: 3746

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

0.10 revamped the Streams API and added the following change in behavior:

WARNING: If you never add a 'data' event handler, or call resume(), then it'll sit in a paused state forever and never emit 'end'.

So, in 0.10, the stream will wait for a valid listener, like a pipe, or a forced resume without an explicit pause.

Steams in 0.8 and older, on the other hand, will start sending 'data' immediately unless instructed to pause. And, in this case, that creates a race condition between the timeout and the stream -- the stream may run in part or even to completion before the timeout expires.

Upvotes: 4

Related Questions