2013-12-17 84 views
0

由於某種原因,當狀態碼不是200並且我返回時,然後調用回調函數,執行的腳本就掛在那裏,而不是退出。這是爲什麼?http.ClientRequest不會結束流

var http = require('http'); 
var qs = require('querystring'); 

var args = { 
    q: 'dfdfdf' 
}; 

var opts = { 
    hostname: 'api.openweathermap.org', 
    path: '/data/2.5/weather?' + qs.stringify(args) 
}; 
function cb(err, result) { 
    console.log(err, result); 
} 

http.get(opts, function(res) { 
    var buffer = new Buffer(0); 

    if (res.statusCode !== 200) return cb(new Error('Unable to fulfill request.')); 

    res.on('readable', function() { 
    return buffer = Buffer.concat([buffer, this.read()]); 
    }); 

    res.on('end', function() { 
    return cb(null, JSON.parse(buffer.toString('utf8'))); 
    }); 
}); 

命令行:

$ node plugins/weather.js 
[Error: Unable to fulfill request.] undefined 
# I have to ctrl+c at this point 
+0

據我看到的,你不定義爲你定義它'cb'要麼 – Plato

+0

。 – Michelle

+0

你只需要一個請求,如果它不是200,你可以調用'return'並記錄錯誤。沒有進一步的代碼執行 - 哦「爲什麼它不退出」。我的猜測需要結束? – Plato

回答

2

你仍然需要消耗流,直到它發出end事件:

http.get(opts, function(res) { 
    var buffer = new Buffer(0); 

    res.on('readable', function() { 
    return buffer = Buffer.concat([buffer, this.read()]); 
    }); 

    res.on('end', function() { 
    if (res.statusCode !== 200) return cb(new Error('Unable to fulfill request.')) 
    return cb(null, buffer.toString()); 
    }); 
}); 
+0

aha,謝謝! – Michelle

0

你永遠不會調用res.end()。您應該在res.end()之前撥打res.write的電話。

+0

我沒有讓你失望。 – Michelle

+0

您可以使用標準的'http'庫將數據傳遞給'res.end()'嗎?你可以用表達例如'res.end(200,'

awesome!

')' – Plato

+0

我希望downvoters更詳細。 –