如何获取 node.js 中图像文件的大小?

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

实际文件大小仅在 'close' 事件发出后可用。您需要先等待管道完成:

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