【问题标题】:Handle unused streams in Node.js处理 Node.js 中未使用的流
【发布时间】:2013-06-18 08:16:09
【问题描述】:

假设我在 Node.js 中使用 http.request 向服务器发送 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();

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

【问题讨论】:

  • 您没有义务编写 on('data') 监听器。但是,您仍将在后台接收此数据,您的节点应用程序只是不知道如何处理它。 .end() 不适用于传入的数据,当您完成向请求发送数据时调用 .end()。
  • 不,我不会在后台接收这些数据(streams2!),只要我不运行 resume() 函数。因此,如果我理解正确,您的评论无济于事:-(
  • 仅仅因为“流”已经暂停,并不意味着网络流量没有发生......你不能阻止网络流量发生,这就是我所指的,并且是的, res.resume() 在这种情况下变得必要,特别是出于同样的原因。你实际上是在告诉流“是的,我知道你已经收到了这些数据,是的,我真的忽略了它,谢谢”
  • 我不希望网络流量“不发生”,我只想让流知道我对它的数据不感兴趣。因此,`res.resume()' 实际上是我应该做的。

标签: node.js stream garbage-collection


【解决方案1】:
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

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

【讨论】:

  • 如上面评论中所述,如果我理解正确的话,对streams2没有帮助。
  • 您唯一需要为流 2 添加的是 res.resume(),这样您就不需要按照您的建议编写 on('data') 侦听器。这一切都是因为我最初的评论:无论你做什么,你都会发送这个数据,除非你物理关闭你的进程,否则它会被接收到。
猜你喜欢
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
相关资源
最近更新 更多