gpt4 book ai didi

javascript - 如果未读取响应,为什么 Node http 客户端会继续运行?

转载 作者:行者123 更新时间:2023-11-30 12:33:31 25 4
gpt4 key购买 nike

我刚刚开始使用 Node.js,我正在尝试编写一个简单的 http 客户端,它只向服务器发送一个 post 请求。

var req = http.request(
{
host : 'localhost',
port: 3000,
url : '/',
method:'POST'

},function(res){
console.log('res status - ' + res.statusCode);
res.on('data', function(){}); //<--------

}
);

(我省略了写入请求和调用 req.end() 的代码)。我观察到如果最后一行被注释掉并且客户端没有读取响应,客户端不会终止。这背后的原因是什么?

最佳答案

此行为是由于以下 Node实现:
发出 http.request() 创建一个具有以下行为的对象 http.ClientRequest

If no 'response' handler(i.e 2nd argument of request method) 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.

关于javascript - 如果未读取响应,为什么 Node http 客户端会继续运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26858135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com