Reputation: 5012
What is the advantage of this way of reading data off a readable stream such as a request:
request.on('readable', function(){
var chunk = null;
while (null !== (chunk = request.read())) {
response.write(chunk);
};
});
vs this way without a while loop inside? Since 'readable' will just keep firing why bother with the while loop?
request.on('readable', function(){
var chunk = request.read();
if(chunk !== null){
response.write(chunk);
}
});
Upvotes: 8
Views: 1278
Reputation: 1658
As per the API documentation:
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
Using the res.on('data') event you get the data when it's ready. This will allow your program to move along and do other things until the next chunk of data is ready to be processed (remember HTTP is over TCP which comes in chunks).
Using the below code might work, but why do that when it's needlessly eating CPU cycles and blocking other code from executing (remember that your Node.js JavaScript code is single-threaded). Using events is far better since it allows your JavaScript to run and process input/output without blocking the process needlessly.
request.on('readable', function(){
var chunk = null;
while (null !== (chunk = request.read())) {
response.write(chunk);
};
});
Upvotes: 1