hassio-nextcloud-backup/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/toolbox.js

22 lines
633 B
JavaScript
Raw Normal View History

// Found on Stackoverflow, perfect code :D https://stackoverflow.com/a/14919494/8654475
2020-11-09 12:42:26 +01:00
function humanFileSize(bytes, si = false, dp = 1) {
const thresh = si ? 1000 : 1024;
2020-11-09 12:42:26 +01:00
if (Math.abs(bytes) < thresh) {
2020-11-09 12:42:26 +01:00
return bytes + " B";
}
2020-11-09 12:42:26 +01:00
const units = si ? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] : ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
let u = -1;
2020-11-09 12:42:26 +01:00
const r = 10 ** dp;
do {
bytes /= thresh;
++u;
} while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);
2020-11-09 12:42:26 +01:00
return bytes.toFixed(dp) + " " + units[u];
}
export { humanFileSize } ;