Search code examples
node.jsfilesize

how to get size of image file in node.js?


I am using below code for download the file and get the size of that download file. Its give me 0 value.But the file is downloaded fine.

var download = function(uri, filename, callback){
  BASE.request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    BASE.request(uri).pipe(BASE.FS.createWriteStream('images/'+filename)).on('close', callback);
      console.log('images/'+filename);
      var stats = BASE.FS.statSync('images/'+filename);
 var fileSizeInBytes = stats["size"];
      console.log(fileSizeInBytes);
 //Convert the file size to megabytes (optional)
 var fileSizeInMegabytes = fileSizeInBytes / 1000000.0;
      console.log(fileSizeInMegabytes);



  });
};


download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
  console.log('done');
});

Solution

  • The actual file size will be available only after the 'close' event has been emitted. You need to wait for the piping to finish first:

    BASE.request(uri).pipe(BASE.FS.createWriteStream('images/'+filename)).on('close', function(err) {
        console.log('images/'+filename);
        var stats = BASE.FS.statSync('images/'+filename);
        var fileSizeInBytes = stats["size"];
        console.log(fileSizeInBytes);
        //Convert the file size to megabytes (optional)
        var fileSizeInMegabytes = fileSizeInBytes / 1000000.0;
        console.log(fileSizeInMegabytes);
    
        callback(err);
    });