SizeFormatHelpers.js 618 B

1234567891011121314151617181920212223242526
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sean Larkin @thelarkinn
  4. */
  5. "use strict";
  6. /**
  7. * Returns the formatted size.
  8. * @param {number=} size the size in bytes
  9. * @returns {string} the formatted size
  10. */
  11. module.exports.formatSize = (size) => {
  12. if (typeof size !== "number" || Number.isNaN(size) === true) {
  13. return "unknown size";
  14. }
  15. if (size <= 0) {
  16. return "0 bytes";
  17. }
  18. const abbreviations = ["bytes", "KiB", "MiB", "GiB"];
  19. const index = Math.floor(Math.log(size) / Math.log(1024));
  20. return `${Number((size / 1024 ** index).toPrecision(3))} ${abbreviations[index]}`;
  21. };