FileSize.js

  1. /**
  2. * Creates a new FileSize
  3. *
  4. * @param {number} bytes Number of bytes
  5. * @constructor
  6. */
  7. function FileSize(bytes) {
  8. /**
  9. * Number of bytes
  10. * @type {number}
  11. */
  12. this.bytes = bytes;
  13. /**
  14. * Returns this.bytes as human-readable file size string
  15. *
  16. * @returns {string} Human-readable file size string
  17. */
  18. this.toReadableString = function() {
  19. return FileSize.getReadableString(this.bytes);
  20. };
  21. }
  22. /**
  23. * List of available size units
  24. *
  25. * @constant
  26. * @type {string[]}
  27. */
  28. FileSize.UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB'];
  29. /**
  30. * 1B in bytes
  31. *
  32. * @constant
  33. * @type {number}
  34. */
  35. FileSize.B = 1;
  36. /**
  37. * 1KB in bytes
  38. *
  39. * @constant
  40. * @type {number}
  41. */
  42. FileSize.KB = 1024 * FileSize.B;
  43. /**
  44. * 1MB in bytes
  45. *
  46. * @constant
  47. * @type {number}
  48. */
  49. FileSize.MB = 1024 * FileSize.KB;
  50. /**
  51. * 1GB in bytes
  52. *
  53. * @constant
  54. * @type {number}
  55. */
  56. FileSize.GB = 1024 * FileSize.MB;
  57. /**
  58. * 1TB in bytes
  59. *
  60. * @constant
  61. * @type {number}
  62. */
  63. FileSize.TB = 1024 * FileSize.GB;
  64. /**
  65. * 1EB in bytes
  66. *
  67. * @constant
  68. * @type {number}
  69. */
  70. FileSize.EB = 1024 * FileSize.TB;
  71. /**
  72. * Returns human-readable file size string from given number of bytes
  73. *
  74. * @param {number} bytes Number of bytes
  75. * @returns {string} Human-readable file size string
  76. */
  77. FileSize.getReadableString = function(bytes) {
  78. let i;
  79. let val = bytes;
  80. for (i = 0; i < FileSize.UNITS.length; i++) {
  81. if(val < 1000) break;
  82. val /= 1024;
  83. }
  84. return (i === 0 ? val : val.toFixed(1)) + FileSize.UNITS[i];
  85. };
  86. export default FileSize;