Stop downloading the data in nodejs request

后端 未结 2 797
名媛妹妹
名媛妹妹 2021-01-05 13:39

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:\'         


        
相关标签:
2条回答
  • 2021-01-05 13:57

    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.

    0 讨论(0)
  • 2021-01-05 13:59

    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();
    
    0 讨论(0)
提交回复
热议问题