2016-11-29 23:45:03 +08:00
|
|
|
/*
|
|
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
|
|
Author Sean Larkin @thelarkinn
|
|
|
|
*/
|
2018-07-30 23:08:51 +08:00
|
|
|
|
2017-02-21 21:52:40 +08:00
|
|
|
"use strict";
|
2016-11-29 23:32:10 +08:00
|
|
|
|
2018-11-09 05:59:19 +08:00
|
|
|
/**
|
|
|
|
* @param {number} size the size in bytes
|
|
|
|
* @returns {string} the formatted size
|
|
|
|
*/
|
2018-07-27 04:37:21 +08:00
|
|
|
exports.formatSize = size => {
|
2018-03-29 21:28:03 +08:00
|
|
|
if (typeof size !== "number" || Number.isNaN(size) === true) {
|
|
|
|
return "unknown size";
|
|
|
|
}
|
|
|
|
|
2018-02-25 09:00:20 +08:00
|
|
|
if (size <= 0) {
|
2016-11-29 23:45:03 +08:00
|
|
|
return "0 bytes";
|
|
|
|
}
|
2016-11-29 23:32:10 +08:00
|
|
|
|
2017-10-09 18:20:20 +08:00
|
|
|
const abbreviations = ["bytes", "KiB", "MiB", "GiB"];
|
|
|
|
const index = Math.floor(Math.log(size) / Math.log(1024));
|
2016-11-29 23:32:10 +08:00
|
|
|
|
2018-02-25 09:00:20 +08:00
|
|
|
return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${
|
|
|
|
abbreviations[index]
|
|
|
|
}`;
|
2017-01-11 17:51:58 +08:00
|
|
|
};
|