Skip to content

Instantly share code, notes, and snippets.

@socheatsok78
Created April 28, 2021 03:55
Show Gist options
  • Save socheatsok78/699d86e3a9d175ce4ab93c3a92da0317 to your computer and use it in GitHub Desktop.
Save socheatsok78/699d86e3a9d175ce4ab93c3a92da0317 to your computer and use it in GitHub Desktop.
Convert Bytes to Human readable file size
export function humanReadableFileSize (bytes, binary = false) {
const base = binary ? 1024 : 1000
if (bytes < base) {
return `${bytes} B`
}
const prefix = binary ? ['Ki', 'Mi', 'Gi'] : ['k', 'M', 'G']
let unit = -1
while (Math.abs(bytes) >= base && unit < prefix.length - 1) {
bytes /= base
++unit
}
return `${bytes.toFixed(1)} ${prefix[unit]}B`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment