Daniel
Daniel

Reputation: 2109

How to find the size of the file in Node.js?

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?

Upvotes: 153

Views: 200254

Answers (6)

Nadav
Nadav

Reputation: 1145

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

Upvotes: 26

Jameel
Jameel

Reputation: 3176

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

Upvotes: 300

Arthur Weborg
Arthur Weborg

Reputation: 8580

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;

Upvotes: 4

Dawson B
Dawson B

Reputation: 1495

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

Upvotes: 3

Lucaci Andrei
Lucaci Andrei

Reputation: 407

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

Upvotes: 1

gerryamurphy
gerryamurphy

Reputation: 179

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

Upvotes: 7

Related Questions