1

假设我http.request在 Node.js 中使用向服务器发送 HTTP 请求,但我唯一感兴趣的是状态码 - 看看它是否有效。我明确感兴趣的是响应流。

所以,基本上我的代码看起来像这样:

var req = https.request(options, {
  method: 'POST',
  path: '/'
}), function (res) {
  // Handle res.statusCode
  callback(null);
});

req.write('Some data ...');
req.end();

我现在的问题是我是否必须对流做任何事情res:我是否必须阅读它,关闭它,...?

我是否需要以下内容:

res.end();

或者

res.resume();

或类似的东西,以确保流已关闭并正确收集垃圾?有什么要注意的吗?

4

1 回答 1

0
var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) { 
    //You do not have to write this listener if you don't want to
    //but NOde will still get all the chunks of data, and attempt to
    //call a callback it will find null, and end up discarding every "chunk"

  });

  res.resume();//Omitting the above(empty ondata listener) and including this line, would exhibit almost identical behavior, res.resume() being very slightly more performant.

  //Not there is no res.end(), even in the version that is processing data
  //Calling end() is the job of the sender, not the receiver
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
//req.end() signifies the end of the data that you are writing to the 
//responding computer.

http://www.infoq.com/news/2013/01/new-streaming-api-node

请参阅上面的链接以获取信息作为参考,了解为什么现在需要这样做。

于 2013-06-18T13:10:38.747 回答