How to Get the Size of a File Using NodeJS

Introduction
How do you get the size of a file using Node.js?
Node.js has a built-in Fs core module that provides an fs.stat() function that lists the statistics for a file at a given path. Using those stats, we will get the file's size in bytes and also convert the bytes value to a human-readable format.
To get the code in this article to work, make sure you have Node.js installed on your local machine.
If you need one, we created a guide on installing Node.js.
Let's get started!
Table of Contents
Get Filesize in Bytes
Before we start running the code, you'll also need a file to work with. So, add one to the root of your project. It can be any type of file you want, such as a JPEG, PNG, PDF, etc.
Once you have a file to work with, open a Node.js file and add this code to it:
Node.js
 
const fs = require("fs")
 
fs.stat("./file.jpg", (err, fileStats) => {
  if (err) {
    console.log(err)
  } else {
    console.log(fileStats)
  }
})
Let's go over each part of that code.
The first thing we do is import the Fs core module. Since this is a Node.js core modules, we don't need to install anything and we can simple require() it and use it right away.
Then, we use the fs.stat() function. The first parameter to the function is a path to the file you want stats for and the second is a callback function that returns an object with all the stats contained in it.
We also do some error handling inside the callback function so an error is logged if one occurs.
The fileStats object returned by the function will look similar to this:
Output
 
{
  dev: 2066,
  mode: 33204,
  nlink: 1,
  uid: 1000,
  gid: 1000,
  rdev: 0,
  blksize: 4096,
  ino: 12204484,
  size: 81151,
  blocks: 160,
  atimeMs: 1570093239638.8958,
  mtimeMs: 1566558056262.4106,
  ctimeMs: 1570093248922.558,
  birthtimeMs: 1570093248922.558,
  atime: 2019-10-03T09:00:39.639Z,
  mtime: 2019-08-23T11:00:56.262Z,
  ctime: 2019-10-03T09:00:48.923Z,
  birthtime: 2019-10-03T09:00:48.923Z
}
To get the size of the file, we can use the size item in the object like this:
Node.js
 
fileStats.size // i.e. 81151
This will return a value in bytes format. But, this isn't very human-friendly.
In the next section, we'll show you a quick function to convert that value into a more human-readable format.
Convert Bytes to Human-Readable Format
At this point, we have a bytes value representing the size of the file. But that value isn't human-readable.
So, let's build a function that takes a bytes value as a parameter and converts it into a formatted and human-readable KB, MB, GB, or TB version.
Here's the code:
Node.js
 
const convertBytes = function(bytes) {
  const sizes = ["Bytes", "KB", "MB", "GB", "TB"]
 
  if (bytes == 0) {
    return "n/a"
  }
 
  const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)))
 
  if (i == 0) {
    return bytes + " " + sizes[i]
  }
 
  return (bytes / Math.pow(1024, i)).toFixed(1) + " " + sizes[i]
}
Before going through the code, it's worth noting that we use 1024 as the base unit for all conversions. We use that number because a kilobyte represents 1024 bytes in the binary system. And a megabyte is 1024 kilobytes and so on.
The first thing we do is create a function named convertBytes() that takes a bytes integer as its sole argument.
Inside the function, we create a sizes array of strings. This will store each of the potential labels (Bytes, Kilobyte, Megabyte, Gigabyte, Terabyte) that we'll use when creating a new string value representing our original bytes parameter value. Each of these will be accessed by their index value later on in the function.
Then, we create an if statement that returns the string "n/a" if the bytes parameter value is equal to zero.
Next, we need to figure out what file type we need to use from the sizes array. The variable named i will represent the index of that string in the sizes array. That value is determined by dividing the log of bytes value by the log of 1024 (file sizes are based on those units).
If the i index value is equal to 0, we'll return a string with the "bytes" label on it.
Otherwise, we'll return a string with the formatted bytes value to one decimal point. And the file type from the sizes array will be added to the end of the string as well.
We can use this function when we use the fs.stat() function and return the bytes file size value.
Here's what the new code would look like with the convertBytes() function included:
Node.js
 
const fs = require("fs")
 
fs.stat("./file.jpg", (err, fileStats) => {
  if (err) {
    console.log(err)
  } else {
    const result = convertBytes(fileStats.size)
    // Example output: 79.2 KB
  }
})
Notice how the result is now formatted into a nicely formatted version as either KB, MB, GB or TB.
Conclusion
For your reference, here is the full code:
Node.js
 
const fs = require("fs")
 
const convertBytes = function(bytes) {
  const sizes = ["Bytes", "KB", "MB", "GB", "TB"]
 
  if (bytes == 0) {
    return "n/a"
  }
 
  const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)))
 
  if (i == 0) {
    return bytes + " " + sizes[i]
  }
 
  return (bytes / Math.pow(1024, i)).toFixed(1) + " " + sizes[i]
}
 
fs.stat("./file.jpg", (err, fileStats) => {
  if (err) {
    console.log(err)
  } else {
    const result = convertBytes(fileStats.size)
    // Example output: 79.2 KB
  }
})
In this article, we showed you how to get the size of a file using Node.js and the Fs core module. And we also created a function that converts the normal bytes value returned by the Fs module into a more human-readable format.
Thanks for reading and happy coding!