How to Get Any File Size in Node.js: Mastering the fs Module

Robin
Updated on March 8, 2023

Getting the size of a file is a simple task, but there are different ways to do it depending on your needs. In Node.js, the fs module provides a powerful set of tools for working with files.

To get the size of any file in Node.js using the fs module, call the fs.stat() method with a path of any file. It will return the file stats object including the size property. This method gives the file size in bytes.

In this post, we'll cover different ways to get the size of a file in Node.js, including asynchronous and synchronous methods. You will also see convert the file size to kilobytes, megabytes, or gigabytes by dividing the byte size by the appropriate factor.

Getting File Size in Node.js Using fs Module

You can retrieve the size of a file using 2 methods from the fs module. The fs.statSync() method works synchronously and the fs.stat() method works asynchronously.

Let's see how can we use both methods with examples:

Using fs.statSync() to Get File Size Synchronously

To use fs.statSync() to get the file size, you can pass the path to the file as an argument to the method. The method will return an object containing information about the file.

You can access the size of the file by accessing the size property of the object. You will get the value in bytes format.

          const fs = require('fs')

const getFileSize = (path) => {
    try {
        const stats = fs.statSync(path)

        console.log(stats)

        return stats.size
    } catch (error) {
        // Handle error here
        console.log(error)
    }
}

const size = getFileSize('./images/banners.jpg')

console.log(size)
// 45712 bytes
        

First, you need to require the fs module inside your script file. Here I have a getFielSize() function that accepts a path (file path) as its argument.

To handle errors, use the try...catch block. If there is no such file in that path or occur any unexpected error, you can handle it inside the catch block.

You can use this path while calling the fs.statSync() method. The stats object returned by the fs.statSync() method contains various file properties. If you check this object, you will see these properties.

          {
  dev: 16777234,
  mode: 33188,
  nlink: 1,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 10199555,
  size: 45712,
  blocks: 96,
  atimeMs: 1678257791675.1821,
  mtimeMs: 1664459737005.8877,
  ctimeMs: 1678257789764.474,
  birthtimeMs: 1664459736455.8765,
  atime: 2023-03-08T06:43:11.675Z,
  mtime: 2022-09-29T13:55:37.006Z,
  ctime: 2023-03-08T06:43:09.764Z,
  birthtime: 2022-09-29T13:55:36.456Z
}
        

As you can see, this object contains a size property. The value of this size property is the size of your file in bytes. I am returning this value from the getFileSize() function.

When I call this function with a path of a file, it will give me the file size. You can convert this byte size into other formats like kilobytes, megabytes, gigabytes, etc.

In this example, I am using an image file but you can use this function with any type of file.

It is important to know that there is a problem with using a synchronous method. When you call a synchronous method, the program will wait for the method to complete before continuing with the next line of code.

That means it will block the execution of the entire program until it completes. This can cause performance issues and make your application slower, especially if you are working with large files or performing time-consuming tasks.

That's why it is better to use asynchronous methods as much as possible for better performance of your application.

Also Read: Synchronous VS Asynchronous Programming with Examples

Using fs.stat() to Get File Size Asynchronously

The fs.stat() method can be used to get the file stats asynchronously, which means that it will not block the event loop. This is the recommended way of getting file size in Node.js, as it is non-blocking and more performant than synchronous methods.

You can call this method in 2 ways:

  • Using callback function.
  • Using promise and async/await syntax.

Callback Function

The fs.stat() method takes 2 arguments: the path of a file and a callback function. Inside this callback function, you will have access to an error object if there is any unexpected error, and an object containing information about the file.

          const fs = require('fs')

const getFileSize = (path, cb) => {
    fs.stat(path, (err, stats) => {
        if (err) {
            // Handle errors here
            console.log(err)
            return
        }

        cb(stats.size)
    })
}

getFileSize('./images/banner.jpg', (fileSize) => {
    console.log(fileSize)
    // 45712 bytes
})
        

In this example, I have a getFileSize() function. I am calling the fs.stat() method using the file path inside this function. If there is any error, you can handle it here.

If there is no error, you can extract the file size value from the stats object. Then I am passing this value to the cb() function.

Finally, when you call the getFileSize() function with a file path, you will get the size of that file inside its callback function.

Promise and async/await Syntax

You can use fs.stat() method with promises and async/await syntax, which can simplify code and make it more readable. You have to require the fs module from fs/promies inside your script file.

          const fs = require('fs/promises')

const getFileSize = async (path) => {
    try {
        const stats = await fs.stat(path)

        return stats.size
    } catch (error) {
        // Handle errors here
        console.log(error)
    }
}

getFileSize('./images/banner.jpg').then((fileSize) => {
    console.log(fileSize)
    // 45712 bytes
})
        

Here I have getFileSize() which is an async function. It takes the path of a file as its argument. I am calling fs.stat() method with the await keyword to wait for Promise to resolve and retrieve the information of that file.

You can use try...catch block for handling any unexpected error.

When you call the getFileSize() method with a file path, you can attach the then() method to it. Here you have access to the file size value.

Also Read: How to Get Image Dimensions (Width and Height) in Node.js

Convert File Size From Byte to KB, MB or GB

As you can see, fs.stat() method gives the file size value in bytes. But often we want to show the value in other formats like kilobytes (KB), megabytes (MB), or gigabytes (GB),

Therefore you have to convert the file size from byte to those other formats. It is very easy to do so.

          const convertBytes = (fileSize, format = 'kb') => {
    const formats = ['kb', 'mb', 'gb']

    let index = formats.indexOf(format.toLowerCase())

    if (index === -1) {
        index = 0
    }

    const multiplier = index + 1

    return parseFloat((fileSize / 1024 ** multiplier).toFixed(2))
}
        

You can use this convertBytes() function to convert your bytes into any of those formats. This function takes the filesize value in bytes and the format you want to convert. Then it will return the formatted value.

          const getFileSize = async (path) => {
    try {
        const stats = await fs.stat(path)

        return stats.size
    } catch (error) {
        // Handle errors here
        console.log(error)
    }
}

getFileSize('./images/banner.jpg').then((fileSize) => {
    console.log(fileSize)

    const fileSizeKB = convertBytes(fileSize, 'kb')
    const fileSizeMB = convertBytes(fileSize, 'mb')
    const fileSizeGB = convertBytes(fileSize, 'gb')

    console.log(fileSizeKB)
    console.log(fileSizeMB)
    console.log(fileSizeGB)
})
        

Now you can call the convertBytes() function and pass your fileSize value to it with the type of format you want.

Also Read: Node.js Cluster: Improve Server Performance with Clustering

Conclusion

There are 2 methods fs.statSync() and fs.stat() in Node.js fs module to find the file size. It's important to choose the appropriate method depending on your use case.

If you need to get the file size synchronously, you can use the fs.statSync() method. However, if you're working with large files, it's better to use the asynchronous fs.stat() method.

It won't block the main thread and will speed up your application. I like to use the fs.stat() method with promises and async/await syntax. Because it's very clean, easy to read, and maintain.

As you will get the size of your file in bytes, you can also convert the file size to a human-readable format such as KB, MB, or GB.

Related Posts