gpt4 book ai didi

node.js - 停止下载nodejs请求中的数据

转载 作者:搜寻专家 更新时间:2023-10-31 22:36:48 25 4
gpt4 key购买 nike

我们如何停止来自服务器的剩余响应 -例如。

http.get(requestOptions, function(response){

//Log the file size;
console.log('File Size:', response.headers['content-length']);

// Some code to download the remaining part of the response?

}).on('error', onError);

我只想记录文件大小,而不是在下载剩余文件时浪费我的带宽。 nodejs 会自动处理这个问题还是我必须为其编写一些特殊代码?

最佳答案

如果你只想获取文件的大小,最好使用HTTP HEAD , 它只返回来自服务器的响应头而没有正文。

您可以像这样在 Node.js 中发出 HEAD 请求:

var http = require("http"),
// make the request over HTTP HEAD
// which will only return the headers
requestOpts = {
host: "www.google.com",
port: 80,
path: "/images/srpr/logo4w.png",
method: "HEAD"
};

var request = http.request(requestOpts, function (response) {
console.log("Response headers:", response.headers);
console.log("File size:", response.headers["content-length"]);
});

request.on("error", function (err) {
console.log(err);
});

// send the request
request.end();

编辑:

我意识到我没有真正回答你的问题,它本质上是“我如何在 Node.js 中尽早终止请求?”。您可以通过调用 response.destroy() 终止处理过程中的任何请求:

var request = http.get("http://www.google.com/images/srpr/logo4w.png", function (response) {
console.log("Response headers:", response.headers);

// terminate request early by calling destroy()
// this should only fire the data event only once before terminating
response.destroy();

response.on("data", function (chunk) {
console.log("received data chunk:", chunk);
});
});

您可以通过注释掉 destroy() 调用并观察在完整请求中返回两个 block 来对此进行测试。然而,正如其他地方提到的,简单地使用 HTTP HEAD 更有效。

关于node.js - 停止下载nodejs请求中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16194017/

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