Node asynchronous stream

This code works for me in Node 0.10, but it doesn't print anything at 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 a 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 the documentation says the pause is advisory, and that bothers me. Why should I pause a thread that is not connected anywhere?

+4
source share
1 answer

0.10 updated the thread API and added the following change in behavior:

WARNING If you never add a 'data' event handler or call resume() , then it will be paused forever and will never emit 'end' .

So, at 0.10, the thread will wait for a valid listener, for example, pipe or forced resume without explicit pause .

Pairs of 0.8 and older, on the other hand, will start sending 'data' immediately if pause not specified. And in this case, this creates a race condition between the timeout and the thread - the thread can be executed partially or even before the timeout expires.

+4
source

Source: https://habr.com/ru/post/1491179/


All Articles