To get the size of a file synchronously, you can use the statSync()
method from the fs
(filesystem) module and then use the size
property from the returned stats
object in Node.js.
Let's say we have a file called myFile.txt
in which you want to get the file size. Here you can use the fs.statSync()
method and pass:
- the
path
to the file as an argument. - the method returns a
stats
object where we can use the property calledsize
to get the file size.
The size
property returns the size of the file in bytes.
It can be done like this,
// require fs module
const fs = require("fs");
// get file size using fs.statSync() method
const stats = fs.statSync("./myFile.txt");
// get size of the file
const size = stats.size;
console.log("File Size is: ", size, "bytes"); // File Size is: 12 bytes
See the above code live in repl.it.
If you want to convert it to mb
, you can divide the size
by 1024 * 1024
like this,
// require fs module
const fs = require("fs");
// get file size using fs.statSync() method
const stats = fs.statSync("./myFile.txt");
// get size of the file
const size = stats.size;
console.log("File Size is: ", size / (1024 * 1024), "mb");
That's it! 😀