Reputation: 129
I am new to node.js. While trying to make a http request using GET method via node the program prints "Got Response: 302" and remains there without exiting. As per code it has to come out of node after printing it. Not able to understand the reason for node waiting for something without exiting the program.
var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
Upvotes: 1
Views: 87
Reputation: 106698
By default in node v0.10+, Readable streams start out in a paused state to prevent data loss. So if there is response data waiting you need to drain the response for the process to exit naturally:
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
// this forces streams1 behavior and starts emitting 'data' events
// which we ignore, effectively draining the stream ...
res.resume();
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
Upvotes: 2
Reputation: 382102
You need to read or cancel the answer or it stays pending :
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function (chunk) {
// you might want to use chunk
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
Note that the http.get official documentation is clearly lacking here.
Upvotes: 1