节点程序不能退出

我是node.js的新手 当试图通过节点使用GET方法发出一个http请求时,程序打印出“Got Response:302”并保持在那里而不退出。 根据代码,打印后必须从节点出来。 无法理解节点在不退出程序的情况下等待的原因。

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

默认情况下,在节点v0.10 +中,可读stream开始时处于暂停状态,以防数据丢失。 所以如果有响应数据等待,你需要排除响应,以便自然退出进程:

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

您需要阅读或取消答案或保持待定状态:

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

请注意, http.get官方文档在这里显然是缺乏的。