gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:08:10 25 4
gpt4 key购买 nike

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

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
});
});

我想在第一个 block 之后完全停止接收响应,但我没有看到任何关闭或结束方法,只有暂停和恢复。我担心使用暂停是对这个响应的引用将无限期地徘徊。

有什么想法吗?

最佳答案

把它放到一个文件中并运行它。如果您看到来自 google 的 301 重定向答案(我相信它是作为单个 block 发送的),您可能需要调整到本地 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.
});
});

要查看 res.destroy() 确实有效,请取消注释它,响应对象将继续发出事件,直到它自己关闭(此时 Node 将退出此脚本)。

我还尝试了 res.emit('end'); 而不是 destroy(),但在我的一次测试运行期间,它仍然触发了一些额外的 block 回调。 destroy() 似乎是一个更迫在眉睫的“终结”。

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

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

关于javascript - 如何提前结束 node.js http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11761542/

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