javascript 如何提前结束 node.js http 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11761542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:16:07  来源:igfitidea点击:

How to end a node.js http request early

javascriptnode.js

提问by Stuart Memo

I'm requesting a remote file using an https.requestin node.js. I'm not interested in receiving the whole file, I just want what's in the first chunk.

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

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.

我想在第一个块之后完全停止接收响应,但我没有看到任何 close 或 end 方法,只有暂停和恢复。我担心使用 pause 是对这个响应的引用将无限期地挂起。

Any ideas?

有任何想法吗?

回答by rdrey

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.)

将其弹出到文件中并运行它。如果您看到来自 google 的 301 重定向答案(我相信它是作为单个块发送的),您可能需要适应本地的 google。

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');instead of the destroy(), but during one of my test runs, it still fired a few additional chunk callbacks. destroy()seems to be a more imminent "end".

我还尝试了res.emit('end');代替destroy(),但在我的一次测试运行期间,它仍然触发了一些额外的块回调。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(它说明响应对象实现了可读流接口。)