137

I am using multer for uploading my images and documents but this time I want to restrict uploading if the size of the image is >2mb. How can I find the size of the file of the document? So far I tried as below but not working.

var storage = multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, common.upload.student);
      },
      filename: function (req, file, callback) {  
        console.log(file.size+'!!!!!!!!!!!!!!')======>'Undefined'
        var ext = '';
        var name = '';
        if (file.originalname) {
          var p = file.originalname.lastIndexOf('.');
          ext = file.originalname.substring(p + 1);
          var firstName = file.originalname.substring(0, p + 1);
          name = Date.now() + '_' + firstName;
          name += ext;
        }
        var filename = file.originalname;
        uploadImage.push({ 'name': name });
        callback(null, name);
  }
});

Can anyone please help me?

Mika Sundland
  • 18,120
  • 16
  • 38
  • 50
Daniel
  • 1,939
  • 3
  • 11
  • 18

6 Answers6

275

To get a file's size in megabytes:

var fs = require("fs"); // Load the filesystem module
var stats = fs.statSync("myfile.txt")
var fileSizeInBytes = stats.size;
// Convert the file size to megabytes (optional)
var fileSizeInMegabytes = fileSizeInBytes / (1024*1024);

or in bytes:

function getFilesizeInBytes(filename) {
    var stats = fs.statSync(filename);
    var fileSizeInBytes = stats.size;
    return fileSizeInBytes;
}
aeronaut
  • 53
  • 1
  • 7
Jameel
  • 2,926
  • 1
  • 12
  • 11
  • 45
    For people searching in 2020+, we now have `(await fs.promises.stat(file)).size`. – garrettmills Nov 27 '20 at 05:36
  • 8
    Links to official docs for convenience: [fs.stat](https://nodejs.org/api/fs.html#fs_fs_stat_path_options_callback) and [fs.promises.stat](https://nodejs.org/api/fs.html#fs_fspromises_stat_path_options) – Akseli Palén Apr 26 '21 at 11:38
  • 1
    To convert to MB it should be `fileSizeInBytes / (1024 * 1000)`. See the last example on https://nodejs.dev/learn/nodejs-file-stats. – Raine Revere May 19 '22 at 13:14
25

If you use ES6 and deconstructing, finding the size of a file in bytes only takes 2 lines (one if the fs module is already declared!):

const fs = require('fs');
const {size} = fs.statSync('path/to/file');

Note that this will fail if the size variable was already declared. This can be avoided by renaming the variable while deconstructing using a colon:

const fs = require('fs');
const {size: file1Size} = fs.statSync('path/to/file1');
const {size: file2Size} = fs.statSync('path/to/file2');
Nadav
  • 1,055
  • 1
  • 10
  • 23
  • But how do you display this? console.log(stats.size()) is failing. – webs Jan 26 '22 at 10:52
  • @webs Are you perhaps commenting on the wrong answer? I didn't use stats in my examples. As for my first example, You can output the result with console.log(size); – Nadav Jan 27 '22 at 09:40
7

In addition, you can use the NPM filesize package: https://www.npmjs.com/package/filesize

This package makes things a little more configurable.

var fs = require("fs"); //Load the filesystem module

var filesize = require("filesize"); 

var stats = fs.statSync("myfile.txt")

var fileSizeInMb = filesize(stats.size, {round: 0});

For more examples:
https://www.npmjs.com/package/filesize#examples

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
gerryamurphy
  • 179
  • 4
  • 6
  • the size is in KB, not MB; stats.size gives bytes, filesize(stats.size, {round: 0}) give KB, the output - if you have stats.size 218871 it makes filesize(stats.size, {round: 0}) = '214 KB' ```// list files with sizes: fs.readdir('.', (err, files) => { files.forEach(file => { var stats = fs.statSync(file); var fileSizeInKb = filesize(stats.size, {round: 0}); console.log('%s --- %s ', file, fileSizeInKb); }); });``` – Sasha Bond Dec 12 '19 at 16:21
  • @SashaBond nah. I think filesize is a module for human readable values. Depending on the file size if it's small or huge it will display the size using KB or MB, try it yourself. – vdegenne May 06 '20 at 17:26
4

For anyone looking for a current answer with native packages, here's how to get mb size of a file without blocking the event loop using fs (specifically, fsPromises) and async/await:

const fs = require('fs').promises;
const BYTES_PER_MB = 1024 ** 2;

// paste following snippet inside of respective `async` function
const fileStats = await fs.stat('/path/to/file');
const fileSizeInMb = fileStats.size / BYTES_PER_MB;
Arthur Weborg
  • 8,280
  • 5
  • 30
  • 67
2

The link by @gerryamurphy is broken for me, so I will link to a package I made for this.

https://github.com/dawsbot/file-bytes

The API is simple and should be easily usable:

fileBytes('README.md').then(size => {
    console.log(`README.md is ${size} bytes`);
});
Pang
  • 9,564
  • 146
  • 81
  • 122
Dawson B
  • 1,224
  • 12
  • 16
1

You can also check this package from npm: https://www.npmjs.com/package/file-sizeof

The API is quite simple, and it gives you the file size in SI and IEC notation.

const { sizeof } = require("file-sizeof");

const si = sizeof.SI("./testfile_large.mp4");
const iec = sizeof.IEC("./testfile_large.mp4");

And the resulting object represents the size from B(byte) up to PB (petabyte).

interface ISizeOf {
  B: number;
  KB: number;
  MB: number;
  GB: number;
  TB: number;
  PB: number;
}
Lucaci Andrei
  • 398
  • 9
  • 20