How to find the size of the file in Node.js?
To get a file's size in megabytes:
var fs = require("fs"); // Load the filesystem modulevar 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;}
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');
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 modulevar 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