Search code examples
javascriptnode.jskeystonejs

How to get file size using url, in nodejs


I have some images in url(s). I can get file properties and properties include width and height of image as well. I want to get the size in bytes.

I am trying to get size using fs module as shown below, but it is not working with url, though it works with file path in local folder.

var stats = fs.statSync(url);
var fileSizeInBytes = stats["size"]

Solution

  • You have to use request, or http. You can get the file size by sending a HEAD request and inspect content-length field (it will not work on every server):


    With curl:

    curl -I "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"
    

    You get the response:

    HTTP/1.1 200 OK
    Date: Tue, 03 Apr 2018 14:30:16 GMT
    Content-Type: application/javascript; charset=utf-8
    Content-Length: 9068
    Connection: keep-alive
    Last-Modified: Wed, 28 Feb 2018 04:16:30 GMT
    ETag: "5a962d1e-236c"
    Expires: Sun, 24 Mar 2019 14:30:16 GMT
    Cache-Control: public, max-age=30672000
    Access-Control-Allow-Origin: *
    CF-Cache-Status: HIT
    Accept-Ranges: bytes
    Strict-Transport-Security: max-age=15780000; includeSubDomains
    Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
    Server: cloudflare
    CF-RAY: 405c3b6e1911a8db-CDG
    

    With request module :

    var request = require("request");
    
    request({
        url: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js",
        method: "HEAD"
    }, function(err, response, body) {
        console.log(response.headers);
        process.exit(0);
    });
    

    You get the response:

    {
      date: 'Tue, 03 Apr 2018 14:29:32 GMT',
      'content-type': 'application/javascript; charset=utf-8',
      'content-length': '9068',
      connection: 'close',
      'last-modified': 'Wed, 28 Feb 2018 04:16:30 GMT',
      etag: '"5a962d1e-236c"',
      expires: 'Sun, 24 Mar 2019 14:29:32 GMT',
      'cache-control': 'public, max-age=30672000',
      'access-control-allow-origin': '*',
      'cf-cache-status': 'HIT',
      'accept-ranges': 'bytes',
      'strict-transport-security': 'max-age=15780000; includeSubDomains',
      'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
      server: 'cloudflare',
      'cf-ray': '405c3a5cba7a68ba-CDG'
    }