Stop loading data in nodejs request

How to stop the remaining response from the server - For example,

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 write the file size and not waste my bandwidth when downloading the remaining file. Does nodejs automatically handle this or do I need to write special code for it?

+5
source share
2 answers

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

You can make a HEAD request in Node.js as follows:

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:

, , : " 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() , . , , HTTP HEAD.

+9

HEAD get

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

All Articles