fileSize.js 744 B

12345678910111213141516171819202122232425
  1. var isStr = require('./isStr');
  2. var toNum = require('./toNum');
  3. exports = function(bytes) {
  4. if (isStr(bytes)) {
  5. var match = bytes.match(regStrSize);
  6. if (!match) return 0;
  7. return Math.round(toNum(match[1]) * factor[match[2] || 'B']);
  8. } else {
  9. if (bytes <= 0) return '0';
  10. var suffixIdx = Math.floor(Math.log(bytes) / Math.log(1024));
  11. var val = bytes / Math.pow(2, suffixIdx * 10);
  12. return +val.toFixed(2) + suffixList[suffixIdx];
  13. }
  14. };
  15. var factor = {
  16. B: 1,
  17. K: 1024
  18. };
  19. factor.M = factor.K * 1024;
  20. factor.G = factor.M * 1024;
  21. factor.T = factor.G * 1024;
  22. var suffixList = ['', 'K', 'M', 'G', 'T'];
  23. var regStrSize = /^(\d+(?:\.\d+)?) *(K|M|G|T)?$/;
  24. module.exports = exports;