Node.js:如何在检索数据时closures响应/请求(块)
我在node.js中build立一个应用程序,加载几个页面,分析内容。
因为node.js发送块,我可以分析块。 如果一个块包含例如索引,nofollow我想closures那个连接,并继续其余的。
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); });
我无法弄清的唯一的事情就是退出这个连接。 或停止检索数据,因为我不需要它..
req.end(); 不工作..它继续检索数据/块..(在我的testing中,我得到14块,但在第一块我已经知道我不需要其他块,所以我想退出请求/响应)。
我现在有一个布尔值,跳过分析其他块,但在我看来,我更好地跳过检索数据?
要调用什么函数? 或者是不可能的,因为它需要检索一切?
我还没有testing过,把这个在你的else
块应该工作: res.removeAllListeners('data');
基本上你的res
是EventEmitter
对象的孩子。 通过调用removeAllListeners('data')
,绑定到data
事件的所有处理程序将被移除,callback将不再执行。 但是,在请求发出end
或error
事件之前,您仍然必须等待所有数据事件通过。
另请阅读nodejs EventEmitter文档以获取更多信息。
更新:
你也可以尝试在你的else块的res
对象上发出end
或close
事件,像这样: res.emit('end');
或res.emit('close');
。 clientResponse对象的文档说明它是
每个响应只发射一次。 之后,在响应中将不再发布“数据”事件。