停止在nodejs请求中下载数据

tus*_*ath 5 httpresponse httprequest node.js

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

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);
Run Code Online (Sandbox Code Playgroud)

我只想记录文件大小而不是浪费我的带宽来下载剩余的文件.nodejs是自动处理这个还是我必须为它编写一些特殊代码?

Rob*_*ell 12

如果您只想获取文件的大小,最好使用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();
Run Code Online (Sandbox Code Playgroud)

编辑:

我意识到我并没有真正回答你的问题,这本质上是"如何在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); 
    });
});
Run Code Online (Sandbox Code Playgroud)

您可以通过注释掉destroy()调用并在完整请求中观察返回两个块来测试它.然而,就像其他地方提到的那样,简单地使用HTTP HEAD更有效.