formatSize.js 766 B

1234567891011121314151617181920212223242526272829303132
  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. const 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", "TiB", "PiB"];
  19. // clamp so sizes beyond the largest unit don't index past the table
  20. const index = Math.min(
  21. Math.floor(Math.log(size) / Math.log(1024)),
  22. abbreviations.length - 1
  23. );
  24. return `${Number((size / 1024 ** index).toPrecision(3))} ${abbreviations[index]}`;
  25. };
  26. module.exports = formatSize;