Created
April 28, 2021 03:55
-
-
Save socheatsok78/699d86e3a9d175ce4ab93c3a92da0317 to your computer and use it in GitHub Desktop.
Convert Bytes to Human readable file size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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