You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
800 B

  1. /**
  2. * Parse byte `size` string.
  3. *
  4. * @param {String} size
  5. * @return {Number}
  6. * @api public
  7. */
  8. module.exports = function(size) {
  9. if ('number' == typeof size) return convert(size);
  10. var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb)$/)
  11. , n = parseFloat(parts[1])
  12. , type = parts[2];
  13. var map = {
  14. kb: 1 << 10
  15. , mb: 1 << 20
  16. , gb: 1 << 30
  17. };
  18. return map[type] * n;
  19. };
  20. /**
  21. * convert bytes into string.
  22. *
  23. * @param {Number} b - bytes to convert
  24. * @return {String}
  25. * @api public
  26. */
  27. function convert (b) {
  28. var gb = 1 << 30, mb = 1 << 20, kb = 1 << 10;
  29. if (b >= gb) return (Math.round(b / gb * 100) / 100) + 'gb';
  30. if (b >= mb) return (Math.round(b / mb * 100) / 100) + 'mb';
  31. if (b >= kb) return (Math.round(b / kb * 100) / 100) + 'kb';
  32. return b + 'b';
  33. }