← coderrocketfuel.com

How To Convert Bytes To KB, MB, GB, Or TB Format In Node.js

How do you convert a bytes value to a formatted and human-readable KB, MB, GB, or TB version in Node.js?

In this article, we'll create a function that'll make converting your bytes values into a human-readable format a piece of cake!

We'll give you the function and explain everything afterward.

Here's the code:

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.

Here are some examples of the function in practice:

convertBytes(0)              // "n/a"
convertBytes(500)            // "500 Bytes"
convertBytes(2000)           // "1.0 KB"
convertBytes(2024000)        // "1.9 MB"
convertBytes(2550024000)     // "2.4 GB"
convertBytes(1292550024000)  // "1.2 TB"

As you can see, the function works as expected in providing a given bytes integer into a human-readable format.

Thanks for reading and happy coding!