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