gpt4 book ai didi

javascript - Node.js:如何在检索数据( block )时关闭响应/请求

转载 作者:搜寻专家 更新时间:2023-10-31 22:50:48 33 4
gpt4 key购买 nike

我正在用 node.js 构建一个应用程序,它加载多个页面并分析内容。

因为 node.js 发送 block 我可以分析 block 。如果一个 block 包含例如索引,nofollow 我想关闭该连接并继续其余部分。

var host  = 'example.com',
total = '',
http = require('http');

var req = http.request({hostname: host, port: 80, path: '/'}, function(res) {
res.on('data', function(chunk) {
total += chunk;
if(chunk.toString().indexOf('index,nofollow') == -1) {
// do stuff
} else {
/*
* WHAT TO DO HERE???
* how to close this res/req?
* close this request (goto res.end or req.end????
*/
}
}).on('end', function() {
// do stuff
});
}).on('error', function(e) {
// do stuff
console.log("Got error: " + e.message);
});

我唯一想不通的是退出该连接。或者停止检索数据,因为我不需要它..

请求结束();不起作用..它继续检索数据/ block ..(在我的测试中我得到了 14 个 block ,但在第一个 block 我已经知道我不需要其他 block ,所以我想退出请求/响应)。

我现在有一个跳过分析其他 block 的 bool 值,但我认为我最好跳过检索数据?

调用什么函数?还是不可能因为它需要检索所有内容?

最佳答案

我还没有测试过,把它放在你的 else block 中应该可以工作:res.removeAllListeners('data');

基本上您的 resEventEmitter 对象的子对象。通过对其调用 removeAllListeners('data'),所有绑定(bind)到 data 事件的处理程序将被删除,回调将不再执行。但是在请求发出 enderror 事件之前,您仍然需要等待所有数据事件通过。

另请阅读 nodejs EventEmitter documentation了解更多信息。

更新:

您不妨尝试在 else block 中的 res 对象上发出 endclose 事件,如下所示: res .emit('end');res.emit('close');documentation on clientRespone end 事件的对象表示它是

Emitted exactly once for each response. After that, no more 'data' events will be emitted on the response.

关于javascript - Node.js:如何在检索数据( block )时关闭响应/请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459644/

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