Convert a bytes value into KB/MB/GB/TB using JavaScript?

Answered
looper003 asked this question 21 days ago
looper003 21 days ago

I'm dealing with file sizes in my JavaScript code where I'm given a value in bytes.

How can I convert that bytes value into a human readable version with gb, mb, kb, etc. denominations?

4 suggested answers
nick 15 days ago

Below is a function you can use to do this conversion for you:

const convertBytesToHumanFormat = 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]
}

convertBytesToHumanFormat(0)             // "n/a"
convertBytesToHumanFormat(500)           // "500 Bytes"
convertBytesToHumanFormat(2048)          // "2.0 KB"
convertBytesToHumanFormat(205900)        // "201.1 KB"
convertBytesToHumanFormat(2550024000)    // "2.4 GB"
convertBytesToHumanFormat(1432150024020) // "1.3 TB"
0 replies
yaboy01 15 days ago

pretty-bytes is a good NPM package that will do the trick for you:

npm install pretty-bytes

Then, you can use it like this:

const prettyBytes = require("pretty-bytes")

prettyBytes(450) // "450 B"
prettyBytes(1021) // "1.02 kB"
prettyBytes(1412432) // "1.41 MB"
prettyBytes(321343423432) // "321 GB"

There are some additional options you can pass to the prettyBytes() function. You can read about them in their documentation.

0 replies
itsbambi 15 days ago
function humanFileSize(size) {
    let i = size == 0 ? 0 : Math.floor(Math.log(size) / Math.log(1024))
    return (size / Math.pow(1024, i)).toFixed(2) * 1 + " " + ["B", "kB", "MB", "GB", "TB"][i]
}
0 replies
suparman21 15 days ago

The filesize.js NPM package is a great tool that will handle everything for you.

Install via:

npm install filesize

And use it like this:

const filesize = require("filesize")

filesize(550) // "550 B"
filesize(12123) // "12.12 KB"
filesize(98174519875) // "98.17 GB"
0 replies
Answered