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