Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *