# Code coverage report for thinkjs/lib/Common/common.js

## Statements: 100% (260 / 260) Branches: 96.67% (145 / 150) Functions: 100% (44 / 44) Lines: 100% (260 / 260) Ignored: none

All files » thinkjs/lib/Common/ » common.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
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    5682
    2
    2
    2
    2

    2
    1

    2

    82
    1
    854
    4467
    4467

    854

    852

    854

    854
    854
    854

    82
    82
    83
    57

    83
    80
    671
    671
    591

    80

    83

    82
    58

    58
    58

    82
    1
    1

    82
    58

    82

    162
    1
    1

    161
    161
    1
    1

    160
    1
    1

    159
    1

    159
    159
    116

    159
    157

    159
    159
    159
    159

    36
    36

    121
    121

    1
    1

    1

    159
    116
    116

    159

    82
    79

    82

    2

    3559
    3559
    3559
    3559
    1130
    1130

    3559
    3559
    3559
    3559
    4310
    4310
    1

    4310
    6926
    6926
    6926
    656

    6270
    1059
    389
    389

    670

    1059
    5211
    5211

    3559

    2

    2

    4731

    2

    1595

    2

    11491
    4

    11487

    2

    8823

    2

    7319

    2

    5

    2

    53

    2

    10

    2

    1715
    914
    914
    649

    265
    801
    251
    550
    12
    538
    30
    508
    464
    44
    43

    1

    2

    961

    2

    2
    2
    2

    2

    370
    240

    130
    130

    2

    368
    25

    343
    343

    2

    2
    2

    28

    2

    1387

    2

    3
    1

    2
    2
    2
    2
    2
    2
    2

    2

    414
    414
    163
    163

    251
    251
    160

    91
    91

    251

    2

    162
    1

    161
    161
    161
    1

    160
    176
    176
    117

    59
    59
    59

    59

    160
    160
    159
    159
    159
    159

    159

    158

    2

    161

    2

    221
    221
    1

    220

    2

    31
    3

    28

    2

    12
    12
    12

    2

    2713
    2713

    2

    862
    862
    862

    2

    1

    2

    1382
    16

    1366
    45

    1321

    2

    563
    563
    563
    563

    563

    2

    83
    83
    65
    65

    18
    35

    18

    2

    4
    4
    4
    8
    8
    4
    4
    2

    2

    4
     var fs = require('fs');
    var path = require('path');
    var util = require('util');
    var crypto = require('crypto');
    var net = require('net');

    /**
     * Promise，后续Node.js会默认支持Promise，所以这里加个判断
     * @type {[type]}
     */
    if (!global.Promise) {
      global.Promise = require('es6-promise').Promise;
    }

    /**
     * 动态创建一个类
     * 提供了继承、扩展、调用父级别方法等方法
     * @return {[type]} [description]
     */
    global.Class = function (prop, superCls) {
      'use strict';
      var cls = function () {
        function T(args) {
          for(var name in cls.__prop){
            var val = cls.__prop[name];
            this[name] = isObject(val) ? extend({}, val) : val;
          }
          //自动执行init方法
          if(isFunction(this.init)){
            //获取init返回值，如果返回一个promise，可以让后续执行在then之后
            this.__initReturn = this.init.apply(this, args);
          }
          return this;
        }
        T.prototype = cls.prototype;
        T.constructor = cls;
        return new T(arguments);
      };
      //类的属性，不放在原型上，实例化的时候调用
      cls.__prop = {};
      cls.extend = function(prop){
        if (isFunction(prop)) {
          prop = prop();
        }
        if (isObject(prop)) {
          for(var name in prop){
            var val = prop[name];
            if (isFunction(val)) {
              this.prototype[name] = val;
            }else{
              cls.__prop[name] = isObject(val) ? extend({}, val) : val;
            }
          }
        }
        return this;
      };
      cls.inherits = function(superCls){
        util.inherits(this, superCls);
        //将父级的属性复制到当前类上
        extend(cls.__prop, superCls.__prop);
        return this;
      };
      if (superCls === true && isFunction(prop)) {
        superCls = prop;
        prop = undefined;
      }
      if (isFunction(superCls)) {
        cls.inherits(superCls);
      }
      //调用父级方法
      cls.prototype.super = cls.prototype.super_ = function(name, data){
        //如果当前类没有这个方法，则直接返回。
        //用于在a方法调用父级的b方法
        if (!this[name]) {
          this.super_c = null;
          return;
        }
        var super_ = this.super_c ? this.super_c.super_ : this.constructor.super_;
        if (!super_) {
          this.super_c = null;
          return;
        }
        //如果父级没有这个方法，那么直接返回
        if (!isFunction(super_.prototype[name])) {
          this.super_c = null;
          return;
        }
        while(this[name] === super_.prototype[name] && super_.super_){
          super_ = super_.super_;
        }
        this.super_c = super_;
        if (!this.super_t) {
          this.super_t = 1;
        }
        //如果参数不是数组，自动转为数组
        if (!isArray(data)) {
          data = arguments.length === 1 ? [] : [data];
        }
        var t = ++this.super_t;
        var method = super_.prototype[name];
        var ret;
        switch(data.length){
          case 0:
            ret = method.call(this);
            break;
          case 1:
            ret = method.call(this, data[0]);
            break;
          case 2:
            ret = method.call(this, data[0], data[1]);
            break;
          default:
            ret = method.apply(this, data);
        }
        if (t === this.super_t) {
          this.super_c = null;
          this.super_t = 0;
        }
        return ret;
      };
      if (prop) {
        cls.extend(prop);
      }
      return cls;
    };
    /**
     * extend, from jquery，具有深度复制功能
     * @return {[type]} [description]
     */
    global.extend = function(){
      'use strict';
      var args = [].slice.call(arguments);
      var deep = true;
      var target = args.shift();
      if (isBoolean(target)) {
        deep = target;
        target = args.shift();
      }
      target = target || {};
      var length = args.length;
      var options, name, src, copy, copyAsArray, clone;
      for(var i = 0; i < length; i++){
        options = args[i] || {};
        if (isFunction(options)) {
          options = options();
        }
        for(name in options){
          src = target[name];
          copy = options[name];
          if (src === copy) {
            continue;
          }
          if (deep && copy && (isObject(copy) || (copyAsArray = isArray(copy) ))) {
            if (copyAsArray) {
              copyAsArray = false;
              clone = src && isArray(src) ? src : [];
            }else{
              clone = src && isObject(src) ? src : {};
            }
            target[name] = extend(deep, clone, copy);
          }else Eif (copy !== undefined) {
            target[name] = copy;
          }
        }
      }
      return target;
    };

    //Object上toString方法
    var toString = Object.prototype.toString;

    /**
     * 是否是boolean
     * @param  {[type]}  obj
     * @return {Boolean}
     */
    global.isBoolean = function(obj){
      'use strict';
      return toString.call(obj) === '[object Boolean]';
    };
    /**
     * 是否是数字
     * @param  {[type]}  obj [description]
     * @return {Boolean}     [description]
     */
    global.isNumber = function(obj){
      'use strict';
      return toString.call(obj) === '[object Number]';
    };
    /**
     * 是否是个对象
     * @param  {[type]}  obj [description]
     * @return {Boolean}     [description]
     */
    global.isObject = function(obj){
      'use strict';
      if (isBuffer(obj)) {
        return false;
      }
      return toString.call(obj) === '[object Object]';
    };
    /**
     * 是否是字符串
     * @param  {[type]}  obj [description]
     * @return {Boolean}     [description]
     */
    global.isString = function(obj){
      'use strict';
      return toString.call(obj) === '[object String]';
    };
    /**
     * 是否是个function
     * @param  {[type]}  obj [description]
     * @return {Boolean}     [description]
     */
    global.isFunction = function(obj){
      'use strict';
      return typeof obj === 'function';
    };
    /**
     * 是否是日期
     * @return {Boolean} [description]
     */
    global.isDate = function(obj){
      'use strict';
      return util.isDate(obj);
    };
    /**
     * 是否是正则
     * @param  {[type]}  reg [description]
     * @return {Boolean}     [description]
     */
    global.isRegexp = function(obj){
      'use strict';
      return util.isRegExp(obj);
    };
    /**
     * 是否是个错误
     * @param  {[type]}  obj [description]
     * @return {Boolean}     [description]
     */
    global.isError = function(obj){
      'use strict';
      return util.isError(obj);
    };
    /**
     * 判断对象是否为空
     * @param  {[type]}  obj
     * @return {Boolean}
     */
    global.isEmpty = function(obj){
      'use strict';
      if (isObject(obj)) {
        var key;
        for(key in obj){
          return false;
        }
        return true;
      }else if (isArray(obj)) {
        return obj.length === 0;
      }else if (isString(obj)) {
        return obj.length === 0;
      }else if (isNumber(obj)) {
        return obj === 0;
      }else if (obj === null || obj === undefined) {
        return true;
      }else if (isBoolean(obj)) {
        return !obj;
      }
      return false;
    };
    /**
     * 是否是个标量
     * @param  {[type]}  obj [description]
     * @return {Boolean}     [description]
     */
    global.isScalar = function(obj){
      'use strict';
      return isBoolean(obj) || isNumber(obj) || isString(obj);
    };
    /**
     * 是否是个数组
     * @type {Boolean}
     */
    global.isArray = Array.isArray;
    /**
     * 是否是IP
     * @type {Boolean}
     */
    global.isIP = net.isIP;
    global.isIP4 = net.isIP4;
    global.isIP6 = net.isIP6;
    /**
     * 是否是个文件
     * @param  {[type]}  p [description]
     * @return {Boolean}   [description]
     */
    global.isFile = function(p){
      'use strict';
      if (!fs.existsSync(p)) {
        return false;
      }
      var stats = fs.statSync(p);
      return stats.isFile();
    };
    /**
     * 是否是个目录
     * @param  {[type]}  p [description]
     * @return {Boolean}   [description]
     */
    global.isDir = function(p){
      'use strict';
      if (!fs.existsSync(p)) {
        return false;
      }
      var stats = fs.statSync(p);
      return stats.isDirectory();
    };
    /**
     * 是否是buffer
     * @type {Boolean}
     */
    global.isBuffer = Buffer.isBuffer;
    /**
     * 是否是个数字的字符串
     * @param  {[type]}  obj [description]
     * @return {Boolean}     [description]
     */
    var numberReg = /^((\-?\d*\.?\d*(?:e[+-]?\d*(?:\d?\.?|\.?\d?)\d*)?)|(0[0-7]+)|(0x[0-9a-f]+))$/i;
    global.isNumberString = function(obj){
      'use strict';
      return numberReg.test(obj);
    };
    /**
     * 判断是否是个promise
     * @param  {[type]}  obj [description]
     * @return {Boolean}     [description]
     */
    global.isPromise = function(obj){
      'use strict';
      return !!(obj && typeof obj.then === 'function');
    };

    /**
     * 判断一个文件或者目录是否可写
     * @param  {[type]}  p [description]
     * @return {Boolean}      [description]
     */
    global.isWritable = function(p){
      'use strict';
      if (!fs.existsSync(p)) {
        return false;
      }
      var stats = fs.statSync(p);
      var mode = stats.mode;
      var uid = process.getuid ? process.getuid() : 0;
      var gid = process.getgid ? process.getgid() : 0;
      var owner = uid === stats.uid;
      var group = gid === stats.gid;
      return !!(owner && (mode & parseInt('00200', 8)) ||
          group && (mode & parseInt('00020', 8)) ||
          (mode & parseInt('00002', 8)));
    };

    /**
     * 递归创建目录，同步模式
     * @param  {[type]} p    [description]
     * @param  {[type]} mode [description]
     * @return {[type]}      [description]
     */
    global.mkdir = function(p, mode){
      'use strict';
      mode = mode || '0777';
      if (fs.existsSync(p)) {
        chmod(p, mode);
        return true;
      }
      var pp = path.dirname(p);
      if (fs.existsSync(pp)) {
        fs.mkdirSync(p, mode);
      }else{
        mkdir(pp, mode);
        mkdir(p, mode);
      }
      return true;
    };
    /**
     * 递归的删除目录，返回promise
     * @param  string p       要删除的目录
     * @param  boolean reserve 是否保留当前目录，只删除子目录
     * @return Promise
     */
    global.rmdir = function(p, reserve){
      'use strict';
      if (!isDir(p)) {
        return getPromise();
      }
      var deferred = getDefer();
      fs.readdir(p, function(err, files){
        if (err) {
          return deferred.reject(err);
        }
        var promises = files.map(function(item){
          var filepath = path.normalize(p + '/' + item);
          if (isDir(filepath)) {
            return rmdir(filepath, false);
          }else{
            var deferred = getDefer();
            fs.unlink(filepath, function(err){
              return err ? deferred.reject(err) : deferred.resolve();
            })
            return deferred.promise;
          }
        })
        var promise = files.length === 0 ? getPromise() : Promise.all(promises);
        return promise.then(function(){
          Eif (!reserve) {
            var deferred = getDefer();
            fs.rmdir(p, function(err){
              return err ? deferred.reject(err) : deferred.resolve();
            })
            return deferred.promise;
          }
        }).then(function(){
          deferred.resolve();
        }).catch(function(err){
          deferred.reject(err);
        })
      })
      return deferred.promise;
    }
    /**
     * 修改目录或者文件权限
     * @param  {[type]} p    [description]
     * @param  {[type]} mode [description]
     * @return {[type]}      [description]
     */
    global.chmod = function(p, mode){
      'use strict';
      mode = mode || '0777';
      if (!fs.existsSync(p)) {
        return true;
      }
      return fs.chmodSync(p, mode);
    };
    /**
     * 获取文件内容
     * @param  {[type]} file [description]
     * @return {[type]}      [description]
     */
    global.getFileContent = function(file, encoding){
      'use strict';
      if (!fs.existsSync(file)) {
        return '';
      }
      return fs.readFileSync(file, encoding || 'utf8');
    };
    /**
     * 设置文件内容
     * @param  {[type]} file [description]
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    global.setFileContent = function(file, data){
      'use strict';
      var filepath = path.dirname(file);
      mkdir(filepath);
      return fs.writeFileSync(file, data);
    };
    /**
     * 大写首字符
     * @param  {[type]} name [description]
     * @return {[type]}      [description]
     */
    global.ucfirst = function(name){
      'use strict';
      name = (name || '') + '';
      return name.substr(0,1).toUpperCase() + name.substr(1).toLowerCase();
    };
    /**
     * 获取字符串的md5
     * @param  {[type]} str [description]
     * @return {[type]}     [description]
     */
    global.md5 = function(str){
      'use strict';
      var instance = crypto.createHash('md5');
      instance.update(str + '');
      return instance.digest('hex');
    };
    /**
     * 获取随机整数
     * @return {[type]} [description]
     */
    global.rand = function(min, max){
      'use strict';
      return Math.floor(min + Math.random() * (max - min + 1));
    }
    /**
     * 生成一个promise,如果传入的参数是promise则直接返回
     * @param  {[type]} obj [description]
     * @return {[type]}     [description]
     */
    global.getPromise = function(obj, reject){
      'use strict';
      if (isPromise(obj)) {
        return obj;
      }
      if (reject) {
        return Promise.reject(obj);
      }
      return Promise.resolve(obj);
    };
    /**
     * 生成一个defer对象
     * @return {[type]} [description]
     */
    global.getDefer = function(){
      'use strict';
      var deferred = {};
      deferred.promise = new Promise(function(resolve, reject){
        deferred.resolve = resolve;
        deferred.reject = reject;
      });
      return deferred;
    };
    /**
     * 快速生成一个object
     * @param  {[type]} key   [description]
     * @param  {[type]} value [description]
     * @return {[type]}       [description]
     */
    global.getObject = function(key, value){
      'use strict';
      var obj = {};
      if (!isArray(key)) {
        obj[key] = value;
        return obj;
      }
      key.forEach(function(item, i){
        obj[item] = value[i];
      });
      return obj;
    };
    /**
     * 将数组变成对象
     * @param  {[type]} arr       [description]
     * @param  {[type]} key       [description]
     * @param  {[type]} valueKeys [description]
     * @return {[type]}           [description]
     */
    global.arrToObj = function(arr, key, valueKey){
      'use strict';
      var result = {};
      var arrResult = [];
      arr.forEach(function(item){
        var keyValue = item[key];
        if (valueKey === null) {
          arrResult.push(keyValue);
        }else if (valueKey) {
          result[keyValue] = item[valueKey];
        }else{
          result[keyValue] = item;
        }
      })
      return valueKey === null ? arrResult : result;
    }