get folder size in megabytes then print it to an express web app (nodejs)

Viewed 31

i need it to print the size of a folder in mb to a express web app

i've already tried it in kb, but i cant figure how to make it work in megabytes

i've tried this

const fs = require('fs');

// Read file stats
fs.stat('file.txt', (err, stats) => {
    if (err) {
        console.log(`File doesn't exist.`);
    } else {
        console.log(stats);
    }
});

and it just prints this

Stats {
  dev: 16777221,
  mode: 33279,
  nlink: 1,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 5172976,
  size: 290,
  blocks: 8,
  atimeMs: 1606143471354.2327,
  mtimeMs: 1599218860000,
  ctimeMs: 1606074010041.4927,
  birthtimeMs: 1605423684000,
  atime: 2020-11-23T14:57:51.354Z,
  mtime: 2020-09-04T11:27:40.000Z,
  ctime: 2020-11-22T19:40:10.041Z,
  birthtime: 2020-11-15T07:
1 Answers

You would do it like this

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

and the you would simply print it like so.

console.log(fileSizeInMegabytes);

and in express you would print it like this.

res.send(fileSizeInMegabytes);
Related