How to find the size of the file in Node JS


In this article, we will see how we can find the size of a file in Node Js.

Node Js provides a file system module (fs) which allows us to work with files on our computer. We can include it in our project using the require() method.

Using the fs modules we can do some common tasks like:

  • read file,
  • create file
  • update file
  • delete a file, and
  • rename file

Now, let's see how we can get the meta-information of a file using this module.

Get file size in megabytes (mb) in node

var fs = require("fs");
var stats = fs.statSync("file.txt")
var sizeInBytes = stats.size;
var sizeInMegabytes = sizeInBytes / (1024*1000);

Using require('fs') we include the file system in our project.

The fs.statSync() synchronously returns information about the given file path.

It returns us an object from where we can get the size information using stats.size .

The stats.size returns the file size in bytes.

You can also use it in an async function using the promise-based fsPromises.stat() method like this

const fs = require('fs/promises');

async function getFileSize() {
  try {
    const stats = await fs.stat('test.txt');
    stats.size; // 1024000 //= 1MB
  } catch (err) {
    console.log(err);
  }
}
getFileSize();

Reference: https://nodejs.dev/learn/nodejs-file-stats


💾 Recommended Articles