index.js 947 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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|tb)$/)
  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. , tb: ((1 << 30) * 1024)
  18. };
  19. return map[type] * n;
  20. };
  21. /**
  22. * convert bytes into string.
  23. *
  24. * @param {Number} b - bytes to convert
  25. * @return {String}
  26. * @api public
  27. */
  28. function convert (b) {
  29. var tb = ((1 << 30) * 1024), gb = 1 << 30, mb = 1 << 20, kb = 1 << 10, abs = Math.abs(b);
  30. if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb';
  31. if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb';
  32. if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb';
  33. if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb';
  34. return b + 'b';
  35. }