http.ClientRequest不会结束流

时间:2013-12-17 17:04:37

标签: node.js

出于某种原因,当状态代码不是200并且我返回然后调用回调时,执行的脚本只是在那里挂起,而不是退出。那是为什么?

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

2 个答案:

答案 0 :(得分: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());
  });
});

答案 1 :(得分:0)

您永远不会致电res.end()。您还应该在res.write之前进行一些res.end()来电。