How to get the size of the file asynchronously using Node.js?

Published April 10, 2021

To get the size of a file asynchronously, you can use the stat() method from the fs (filesystem) module and then use the size property from the 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.stat() method and pass:

  • the path to the file as the first argument.
  • a callback function that will get invoked after statistics about the file is obtained, in which the first parameter is an error object and the second parameter is the stats object which contains all the information about the file.

In our case, the size of the file can be obtained using the size property from the stats object. 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.stat() method
fs.stat("./myFile.txt", (error, stats) => {
  // in case of any error
  if (error) {
    console.log(error);
    return;
  }

  // else show size from stats object
  console.log("File Size is: ", stats.size, "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.stat() method
fs.stat("./myFile.txt", (error, stats) => {
  // in case of any error
  if (error) {
    console.log(error);
    return;
  }

  // else show size from stats object
  console.log("File Size is: ", stats.size / (1024 * 1024), "mb");
});

That's it! 😀

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter