-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathutils.js
123 lines (104 loc) · 2.5 KB
/
utils.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*!
* Cluster - utils
* Copyright (c) 2011 LearnBoost <[email protected]>
* MIT Licensed
*/
var path = require('path')
, fs = require('fs');
/**
* Frame the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
exports.frame = function(obj){
return JSON.stringify(obj) + '\n';
};
/**
* Fast alternative to `Array.prototype.slice.call()`.
*
* @param {Arguments} args
* @param {Number} index
* @return {Array}
* @api private
*/
exports.toArray = function(args, index){
var arr = []
, len = args.length;
for (var i = (index || 0); i < len; ++i) {
arr.push(args[i]);
}
return arr;
};
/**
* Format byte-size.
*
* @param {Number} bytes
* @return {String}
* @api private
*/
exports.formatBytes = function(bytes) {
var kb = 1024
, mb = 1024 * kb
, gb = 1024 * mb;
if (bytes < kb) return bytes + 'b';
if (bytes < mb) return (bytes / kb).toFixed(2) + 'kb';
if (bytes < gb) return (bytes / mb).toFixed(2) + 'mb';
return (bytes / gb).toFixed(2) + 'gb';
};
/**
* Format date difference between `a` and `b`.
*
* @param {Date} a
* @param {Date} b
* @return {String}
* @api private
*/
exports.formatDateRange = function(a, b) {
var diff = a > b ? a - b : b - a
, second = 1000
, minute = second * 60
, hour = minute * 60
, day = hour * 24;
function unit(name, n) {
return n + ' ' + name + (1 == n ? '' : 's');
}
if (diff < second) return unit('millisecond', diff);
if (diff < minute) return unit('second', (diff / second).toFixed(0));
if (diff < hour) return unit('minute', (diff / minute).toFixed(0));
if (diff < day) return unit('hour', (diff / hour).toFixed(0));
return unit('day', (diff / day).toFixed(1));
};
/**
* Unshift a callback.
*
* @param {Object} obj
* @param {String} event
* @param {String} fn
* @api private
*/
exports.unshiftListener = function(obj, event, fn){
if (Array.isArray(obj._events[event])) {
obj._events[event].unshift(fn);
} else {
obj._events[event] = [fn, obj._events[event]];
}
};
/**
* `mkdir -p`, synchronously
*
* @param {String} dir
* @param {String} mode
* @api private
*/
exports.mkdirPSync = function(dir, mode) {
var buildingPath = [],
components = path.normalize(dir).split('/');
components.slice(1, components.length).forEach(function(component) {
buildingPath = buildingPath.concat(component);
var toCreate = '/' + buildingPath.join('/');
if (!path.existsSync(toCreate))
fs.mkdirSync('/' + buildingPath.join('/'), mode);
});
};