如何尽早结束node.js http请求

我在node.js中使用https.request请求远程文件。 我对接收整个文件不感兴趣,我只想要第一个部分的内容。

 var req = https.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (d) { console.log(d); res.pause(); // I want this to end instead of pausing }); }); 

我想在第一个块之后完全不接收响应,但是我没有看到任何closures或结束方法,只能暂停和恢复。 我暂时停下来担心的是,对这个回应的引用将无限期地拖延下去。

有任何想法吗?

在一个文件中popup并运行它。 如果你看到一个来自google的301redirect答案(我认为它是作为一个单独的块发送的),你可能必须调整到你的本地谷歌。

 var http = require('http'); var req = http.get("http://www.google.co.za/", function(res) { res.setEncoding(); res.on('data', function(chunk) { console.log(chunk.length); res.destroy(); //After one run, uncomment this. }); }); 

要看到res.destroy()真正起作用,请取消注释,响应对象将继续发出事件直到它自己closures(此时节点将退出此脚本)。

我也尝试了res.emit('end'); 而不是destroy() ,但在我的一个testing运行,它仍然发射了一些额外的块callback。 destroy()似乎是一个更迫在眉睫的“结束”。

销毁方法的文档在这里: http : //nodejs.org/api/stream.html#stream_stream_destroy

但是你应该从这里开始阅读: http : //nodejs.org/api/http.html#http_http_clientresponse (它声明响应对象实现了可读的stream接口。)