[英]How to end a node.js http request early
I'm requesting a remote file using an https.request
in node.js. 我正在使用node.js中的
https.request
请求远程文件。 I'm not interested in receiving the whole file, I just want what's in the first chunk. 我对接收整个文件不感兴趣,我只想要第一块中的内容。
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
});
});
I want to stop receiving the response altogether after the first chunk, but I don't see any close or end methods, only pause and resume. 我想在第一个块之后完全停止接收响应,但是我没有看到任何关闭或结束方法,只是暂停和恢复。 My worry using pause is that a reference to this response will be hanging around indefinitely.
我使用暂停的担心是,对此响应的引用将无限期地挂起。
Any ideas? 有任何想法吗?
Pop this in a file and run it. 将其弹出一个文件并运行它。 You might have to adjust to your local google, if you see a 301 redirect answer from google (which is sent as a single chunk, I believe.)
你可能需要调整到你的本地谷歌,如果你看到来自谷歌的301重定向答案(我相信,它作为单个块发送。)
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.
});
});
To see that res.destroy()
really works, uncomment it, and the response object will keep emitting events until it closes itself (at which point node will exit this script). 要查看
res.destroy()
确实有效,请取消注释,并且响应对象将继续发出事件,直到它自己关闭(此时节点将退出此脚本)。
I also experimented with res.emit('end');
我还尝试了
res.emit('end');
instead of the destroy()
, but during one of my test runs, it still fired a few additional chunk callbacks. 而不是
destroy()
,但在我的一次测试运行期间,它仍然会触发一些额外的块回调。 destroy()
seems to be a more imminent "end". destroy()
似乎是一个更迫在眉睫的“终结”。
The docs for the destroy method are here: http://nodejs.org/api/stream.html#stream_stream_destroy destroy方法的文档在这里: http : //nodejs.org/api/stream.html#stream_stream_destroy
But you should start reading here: http://nodejs.org/api/http.html#http_http_clientresponse (which states that the response object implements the readable stream interface.) 但是你应该从这里开始阅读: http : //nodejs.org/api/http.html#http_http_clientresponse (它声明响应对象实现了可读的流接口。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.