为什么我们需要 res.on('data'... 为 POST 定义,即使我们没有对数据做任何事情?

Why do we need res.on('data'... defined for POST even if we are not doing anything with the data?

在调试代码时发现此问题,但以下代码不起作用:

var req = http.request(options,function(res){
            // res.on('error',cb(err));
            res.on('end',function(){
                cb();
            });
        });

但是以下确实有效:

       var req = http.request(options,function(res){
            // res.on('error',cb(err));
            res.on('data',function(chunk){
                //why do we need this?
            });
            res.on('end',function(){
                cb();
            });
        });

这就是节点的背压机制的工作原理。如果响应流的缓冲区已满,它会告诉服务器停止发送数据(这是在 TCP 层处理的)。因此,一旦您开始读取数据(通过 res.read() 或附加 data 处理程序或简单地使用 res.resume()),就会从服务器传输更多数据,直到没有更多数据为止。只有当服务器没有更多数据要发送时,您才会收到 end 事件。我通常使用 res.resume();,因为它更短。

自节点 v0.10 以来就存在此行为。在此之前,如果您不立即附加 data 处理程序,您实际上可能会丢失数据,因此您可以想象这会给很多人带来问题。因此,对于节点 v0.10+,默认行为是暂停,直到您开始阅读(这是在节点流层,与网络分开)。

在此实现中,function(res) 是一个回调,它必须至少为 'data''end' 事件注册侦听器,即使它们实际上没有做任何事情。

来自 official documentation:

During the 'response' event, one can add listeners to the response object; particularly to listen for the 'data' event.

If no 'response' handler is added, then the response will be entirely discarded. However, if you add a 'response' event handler, then you must consume the data from the response object, either by calling response.read() whenever there is a 'readable' event, or by adding a 'data' handler, or by calling the .resume() method. Until the data is consumed, the 'end' event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.

res 变量是一个 Readable Stream. If you click the link and scroll down to 'end' event 您可能会发现以下内容:

Note that the 'end' event will not fire unless the data is completely consumed.

通过添加 'data' 事件处理程序,您可以使用数据。