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

Javascriptnode.jsExpressMulter

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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;

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

You can find the size in bytes.

const libFS       = require('fs');
let yourFilesize  = fs.statSync("File path").size
console.log(yourFilesize)

Solution 8 - Javascript

NOTE: The following is within the context of an Electron application.

Using the following:

window.require("fs")

Instead of just:

require("fs")

Resolved this issue for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanielView Question on Stackoverflow
Solution 1 - JavascriptJameelView Answer on Stackoverflow
Solution 2 - JavascriptNadavView Answer on Stackoverflow
Solution 3 - JavascriptgerryamurphyView Answer on Stackoverflow
Solution 4 - JavascriptArthur WeborgView Answer on Stackoverflow
Solution 5 - JavascriptDawson BView Answer on Stackoverflow
Solution 6 - JavascriptLucaci AndreiView Answer on Stackoverflow
Solution 7 - JavascriptAnkit Kumar RajpootView Answer on Stackoverflow
Solution 8 - JavascriptFall BayView Answer on Stackoverflow