How to find the size of the file in Node.js?

Sometimes, we want to find the size of the file in Node.js.

In this article, we’ll look at how to find the size of the file in Node.js.

How to find the size of the file in Node.js?

To find the size of the 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 ** 2);

to call fs.statSync with the path of the file that we want to get the size of.

Then we get the file size in bytes with stats.size.

Next, we convert the size to megabytes with fileSizeInBytes / (1024 ** 2).

Conclusion

To find the size of the file in Node.js, we can use the fs.statSync method.