3 * Copyright(c) 2012-2014 TJ Holowaychuk
4 * Copyright(c) 2015 Jed Watson
15 module.exports = bytes;
16 module.exports.format = format;
17 module.exports.parse = parse;
29 tb: ((1 << 30) * 1024)
33 *Convert the given value in bytes into a string or parse to string to an integer in bytes.
35 * @param {string|number} value
38 * decimalPlaces: [number]
39 * fixedDecimals: [boolean]
40 * thousandsSeparator: [string]
41 * }} [options] bytes options.
43 * @returns {string|number|null}
46 function bytes(value, options) {
47 if (typeof value === 'string') {
51 if (typeof value === 'number') {
52 return format(value, options);
59 * Format the given value in bytes into a string.
61 * If the value is negative, it is kept as such. If it is a float,
64 * @param {number} value
65 * @param {object} [options]
66 * @param {number} [options.decimalPlaces=2]
67 * @param {number} [options.fixedDecimals=false]
68 * @param {string} [options.thousandsSeparator=]
72 function format(value, options) {
73 if (typeof value !== 'number') {
77 var mag = Math.abs(value);
78 var thousandsSeparator = (options && options.thousandsSeparator) || '';
79 var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
80 var fixedDecimals = Boolean(options && options.fixedDecimals);
85 } else if (mag >= map.gb) {
87 } else if (mag >= map.mb) {
89 } else if (mag >= map.kb) {
93 var val = value / map[unit.toLowerCase()];
94 var str = val.toFixed(decimalPlaces);
97 str = str.replace(/(?:\.0*|(\.[^0]+)0+)$/, '$1');
100 if (thousandsSeparator) {
101 str = str.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator);
108 * Parse the string value into an integer in bytes.
110 * If no unit is given, it is assumed the value is in bytes.
112 * @param {number|string} val
116 function parse(val) {
117 if (typeof val === 'number' && !isNaN(val)) {
121 if (typeof val !== 'string') {
125 // Test if the string passed is valid
126 var results = val.match(/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i);
131 // Nothing could be extracted from the given string
132 floatValue = parseInt(val);
135 // Retrieve the value and the unit
136 floatValue = parseFloat(results[1]);
137 unit = results[4].toLowerCase();
140 return map[unit] * floatValue;