-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
474 lines (437 loc) · 9.87 KB
/
index.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const net = require('net');
const cluster = require('cluster');
const uuid = require('uuid');
const ms = require('ms');
const {
isArray,
isBoolean,
isNull,
isNullOrUndefined,
isNumber,
isString,
isSymbol,
isUndefined,
isRegExp,
isObject,
isDate,
isError,
isFunction,
isPrimitive,
isBuffer
} = require('core-util-is');
const fsRmdir = promisify(fs.rmdir, fs);
const fsUnlink = promisify(fs.unlink, fs);
const fsReaddir = promisify(fs.readdir, fs);
const numberReg = /^((-?(\d+\.|\d+|\.\d)\d*(?:e[+-]?\d*(?:\d?\.?|\.?\d?)\d*)?)|(0[0-7]+)|(0x[0-9a-f]+))$/i;
const toString = Object.prototype.toString;
exports.isIP = net.isIP;
exports.isIPv4 = net.isIPv4;
exports.isIPv6 = net.isIPv6;
exports.isMaster = cluster.isMaster;
exports.isArray = isArray;
exports.isBoolean = isBoolean;
exports.isNull = isNull;
exports.isNullOrUndefined = isNullOrUndefined;
exports.isNumber = isNumber;
exports.isString = isString;
exports.isSymbol = isSymbol;
exports.isUndefined = isUndefined;
exports.isRegExp = isRegExp;
exports.isObject = isObject;
exports.isDate = isDate;
exports.isError = isError;
exports.isFunction = isFunction;
exports.isPrimitive = isPrimitive;
exports.isBuffer = isBuffer;
/**
* override isObject method in `core-util-is` module
*/
exports.isObject = obj => {
return toString.call(obj) === '[object Object]';
};
/**
* check value is integer
*/
function isInt(value) {
if (isNaN(value) || exports.isString(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
}
exports.isInt = isInt;
/**
* make callback function to promise
* @param {Function} fn []
* @param {Object} receiver []
* @return {Promise} []
*/
function promisify(fn, receiver) {
return (...args) => {
return new Promise((resolve, reject) => {
fn.apply(receiver, [...args, (err, res) => {
return err ? reject(err) : resolve(res);
}]);
});
};
}
exports.promisify = promisify;
exports.extend = require('lodash.merge');
/**
* camelCase string
* @param {String} str []
* @return {String} []
*/
function camelCase(str) {
if (str.indexOf('_') > -1) {
str = str.replace(/_(\w)/g, (a, b) => {
return b.toUpperCase();
});
}
return str;
}
exports.camelCase = camelCase;
/**
* snakeCase string
* @param {String} str []
* @return {String} []
*/
function snakeCase(str) {
return str.replace(/([^A-Z])([A-Z])/g, function($0, $1, $2) {
return $1 + '_' + $2.toLowerCase();
});
};
exports.snakeCase = snakeCase;
/**
* check object is number string
* @param {Mixed} obj []
* @return {Boolean} []
*/
function isNumberString(obj) {
if (!obj) return false;
return numberReg.test(obj);
}
exports.isNumberString = isNumberString;
/**
* true empty
* @param {Mixed} obj []
* @return {Boolean} []
*/
function isTrueEmpty(obj) {
if (obj === undefined || obj === null || obj === '') return true;
if (exports.isNumber(obj) && isNaN(obj)) return true;
return false;
}
exports.isTrueEmpty = isTrueEmpty;
/**
* check object is mepty
* @param {[Mixed]} obj []
* @return {Boolean} []
*/
function isEmpty(obj) {
if (isTrueEmpty(obj)) return true;
if (exports.isRegExp(obj)) {
return false;
} else if (exports.isDate(obj)) {
return false;
} else if (exports.isError(obj)) {
return false;
} else if (exports.isArray(obj)) {
return obj.length === 0;
} else if (exports.isString(obj)) {
return obj.length === 0;
} else if (exports.isNumber(obj)) {
return obj === 0;
} else if (exports.isBoolean(obj)) {
return !obj;
} else if (exports.isObject(obj)) {
for (const key in obj) {
return false && key; // only for eslint
}
return true;
}
return false;
}
exports.isEmpty = isEmpty;
/**
* get deferred object
* @return {Object} []
*/
function defer() {
const deferred = {};
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
}
exports.defer = defer;
/**
* get content md5
* @param {String} str [content]
* @return {String} [content md5]
*/
function md5(str) {
return crypto.createHash('md5').update(str + '', 'utf8').digest('hex');
}
exports.md5 = md5;
/**
* get timeout Promise
* @param {Number} time []
* @return {[type]} []
*/
function timeout(time = 1000) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
exports.timeout = timeout;
/**
* escape html
*/
function escapeHtml(str) {
return (str + '').replace(/[<>'"]/g, a => {
switch (a) {
case '<':
return '<';
case '>':
return '>';
case '"':
return '"e;';
case '\'':
return ''';
}
});
}
exports.escapeHtml = escapeHtml;
/**
* get datetime
* @param {Date} date []
* @return {String} []
*/
function datetime(date = new Date(), format) {
if (date && isString(date)) {
const dateString = date;
date = new Date(Date.parse(date));
if (isNaN(date.getTime()) && !format) {
format = dateString;
date = new Date();
}
}
format = format || 'YYYY-MM-DD HH:mm:ss';
const fn = d => {
return ('0' + d).slice(-2);
};
const d = new Date(date);
const formats = {
YYYY: d.getFullYear(),
MM: fn(d.getMonth() + 1),
DD: fn(d.getDate()),
HH: fn(d.getHours()),
mm: fn(d.getMinutes()),
ss: fn(d.getSeconds())
};
return format.replace(/([a-z])\1+/ig, a => {
return formats[a] || a;
});
}
exports.datetime = datetime;
/**
* generate uuid
* @param {String} version [uuid RFC version]
* @return {String} []
*/
exports.uuid = function(version) {
if (version === 'v1') return uuid.v1();
return uuid.v4();
};
/**
* parse adapter config
*/
exports.parseAdapterConfig = (config = {}, ...extConfig) => {
config = exports.extend({}, config);
// {handle: ''}
if (!config.type) config.type = '_';
// {type: 'xxx', handle: ''}
if (config.handle) {
const type = config.type;
delete config.type;
config = { type, [type]: config };
}
extConfig = extConfig.map(item => {
if (!item) return {};
// only change type
// 'xxx'
if (exports.isString(item)) {
item = { type: item };
}
// {handle: 'www'}
// only add some configs
if (!item.type) {
item = { type: config.type, [config.type]: item };
}
// {type: 'xxx', handle: 'www'}
if (item.handle) {
const type = item.type;
delete item.type;
item = { type, [type]: item };
}
return item;
});
// merge config
config = exports.extend({}, config, ...extConfig);
const value = config[config.type] || {};
// add type for return value
value.type = config.type;
return value;
};
/**
* transform humanize time to ms
*/
exports.ms = function(time) {
if (typeof time === 'number') return time;
const result = ms(time);
if (result === undefined) {
throw new Error(`think-ms('${time}') result is undefined`);
}
return result;
};
/**
* omit some props in object
*/
exports.omit = function(obj, props) {
if (exports.isString(props)) {
props = props.split(',');
}
const keys = Object.keys(obj);
const result = {};
keys.forEach(item => {
if (props.indexOf(item) === -1) {
result[item] = obj[item];
}
});
return result;
};
/**
* check path is exist
*/
function isExist(dir) {
dir = path.normalize(dir);
try {
fs.accessSync(dir, fs.R_OK);
return true;
} catch (e) {
return false;
}
}
exports.isExist = isExist;
/**
* check filepath is file
*/
function isFile(filePath) {
if (!isExist(filePath)) return false;
try {
const stat = fs.statSync(filePath);
return stat.isFile();
} catch (e) {
return false;
}
}
exports.isFile = isFile;
/**
* check path is directory
*/
function isDirectory(filePath) {
if (!isExist(filePath)) return false;
try {
const stat = fs.statSync(filePath);
return stat.isDirectory();
} catch (e) {
return false;
}
}
exports.isDirectory = isDirectory;
/**
* change path mode
* @param {String} p [path]
* @param {String} mode [path mode]
* @return {Boolean} []
*/
function chmod(p, mode) {
try {
fs.chmodSync(p, mode);
return true;
} catch (e) {
return false;
}
}
exports.chmod = chmod;
/**
* make dir
*/
function mkdir(dir, mode) {
if (isExist(dir)) {
if (mode) return chmod(dir, mode);
return true;
}
const pp = path.dirname(dir);
if (isExist(pp)) {
try {
fs.mkdirSync(dir, mode);
return true;
} catch (e) {
return false;
}
}
if (mkdir(pp, mode)) return mkdir(dir, mode);
return false;
}
exports.mkdir = mkdir;
/**
* get files in path
* @param {} dir []
* @param {} prefix []
* @return {} []
*/
function getdirFiles(dir, prefix = '') {
dir = path.normalize(dir);
if (!fs.existsSync(dir)) return [];
const files = fs.readdirSync(dir);
let result = [];
files.forEach(item => {
const currentDir = path.join(dir, item);
const stat = fs.statSync(currentDir);
if (stat.isFile()) {
result.push(path.join(prefix, item));
} else if (stat.isDirectory()) {
const cFiles = getdirFiles(currentDir, path.join(prefix, item));
result = result.concat(cFiles);
}
});
return result;
};
exports.getdirFiles = getdirFiles;
/**
* remove dir aync
* @param {String} p [path]
* @param {Boolean} reserve []
* @return {Promise} []
*/
function rmdir(p, reserve) {
if (!isDirectory(p)) return Promise.resolve();
return fsReaddir(p).then(files => {
const promises = files.map(item => {
const filepath = path.join(p, item);
if (isDirectory(filepath)) return rmdir(filepath, false);
return fsUnlink(filepath);
});
return Promise.all(promises).then(() => {
if (!reserve) return fsRmdir(p);
});
});
}
exports.rmdir = rmdir;
exports.isBuffer = Buffer.isBuffer;