Sometimes, we want to find the size of a file in Node.js.
In this article, we’ll look at how to find the size of a file in Node.js.
How to find the size of a file in Node.js?
To find the size of a file in Node.js, we can use the fs.statSync
method.
For instance, we write
const fs = require("fs");
const stats = fs.statSync("myfile.txt");
const fileSizeInBytes = stats.size;
const fileSizeInMegabytes = fileSizeInBytes / (1024 * 1024);
to call the fs.statSync
method with the path of the file we want to get the size for.
Then we get the size in bytes with stats.size
.
Next, we convert the number of bytes to megabytes by dividing it by 1024 * 1024
.
Conclusion
To find the size of a file in Node.js, we can use the fs.statSync
method.