Stop downloading the data in nodejs request

2019-02-14 03:05发布

How can we stop the remaining response from a server - For eg.

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

I just want to log the file size and not waste my bandwidth in downloading the remaining file. Does nodejs automatically handles this or do I have to write some special code for it?

2条回答
我只想做你的唯一
2楼-- · 2019-02-14 03:59

If you just want fetch the size of the file, it is best to use HTTP HEAD, which returns only the response headers from the server without the body.

You can make a HEAD request in Node.js like this:

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

EDIT:

I realized that I didn't really answer your question, which is essentially "How do I terminate a request early in Node.js?". You can terminate any request in the middle of processing by calling 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); 
    });
});

You can test this by commenting out the the destroy() call and observing that in a full request two chunks are returned. Like mentioned elsewhere, however, it is more efficient to simply use HTTP HEAD.

查看更多
\"骚年 ilove
3楼-- · 2019-02-14 04:01

You need to perform a HEAD request instead of a get

Taken from this answer

var http = require('http');
var options = {
    method: 'HEAD', 
    host: 'stackoverflow.com', 
    port: 80, 
    path: '/'
};
var req = http.request(options, function(res) {
    console.log(JSON.stringify(res.headers));
    var fileSize = res.headers['content-length']
    console.log(fileSize)
  }
);
req.end();
查看更多
登录 后发表回答