# all files / lib/ tmp.js

74.67% Statements 112/150
65.96% Branches 62/94
81.48% Functions 22/27
76.92% Lines 110/143

    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

    1×

    1×

    1×
    33×

    33×
    33×

    33×
    366×

    33×

    1×
    9×

    1×
    79×
    5×

    5×
    5×
    74×
    4×

    79×

    1×
    37×
    4×

    33×
    5×

    28×

    28×

    1×
    25×

    25×
    4×

    21×

    21×
    21×

    21×
    21×

    21×

    1×
    18×

    18×
    2×

    16×

    16×
    16×
    16×
    16×

    16×

    1×
    9×

    9×

    9×
    9×

    8×
    8×

    8×

    1×
    9×

    9×

    9×
    8×

    8×

    1×

    1×
    9×

    9×
    9×

    8×
    8×

    8×

    1×
    9×

    9×
    8×

    8×

    1×
    16×
    2×
    2×

    2×

    16×
    16×

    16×

    1×
    16×
    16×

    16×
    16×

    16×

    1×
    32×

    32×
    5×

    5×
    5×
    5×

    5×
    5×

    1×

    1×

    1×
    3×

    1×

    1×

    1×
    1×
    1×
    1×
    1×
    1×
    1×
    1×
     /*!
     * Tmp
     *
     * Copyright (c) 2011-2015 KARASZI Istvan <github@spam.raszi.hu>
     *
     * MIT Licensed
     */

    /**
     * Module dependencies.
     */
    var
      fs     = require('fs'),
      path   = require('path'),
      crypto = require('crypto'),
      tmpDir = require('os-tmpdir'),
      _c     = require('constants');

    /**
     * The working inner variables.
     */
    var
      // store the actual TMP directory
      _TMP = tmpDir(),

      // the random characters to choose from
      RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',

      TEMPLATE_PATTERN = /XXXXXX/,

      DEFAULT_TRIES = 3,

      CREATE_FLAGS = _c.O_CREAT | _c.O_EXCL | _c.O_RDWR,

      DIR_MODE = 448 /* 0700 */,
      FILE_MODE = 384 /* 0600 */,

      // this will hold the objects need to be removed on exit
      _removeObjects = [],

      _gracefulCleanup = false,
      _uncaughtException = false;

    /**
     * Random name generator based on crypto.
     * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript
     *
     * @param {Number} howMany
     * @return {String}
     * @api private
     */
    function _randomChars(howMany) {
      var
        value = [],
        rnd = null;

      // make sure that we do not fail because we ran out of entropy
      try {
        rnd = crypto.randomBytes(howMany);
      } catch (e) {
        rnd = crypto.pseudoRandomBytes(howMany);
      }

      for (var i = 0; i < howMany; i++) {
        value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
      }

      return value.join('');
    }

    /**
     * Checks whether the `obj` parameter is defined or not.
     *
     * @param {Object} obj
     * @return {Boolean}
     * @api private
     */
    function _isUndefined(obj) {
      return typeof obj === 'undefined';
    }

    /**
     * Parses the function arguments.
     *
     * This function helps to have optional arguments.
     *
     * @param {Object} options
     * @param {Function} callback
     * @api private
     */
    function _parseArguments(options, callback) {
      if (typeof options == 'function') {
        var
          tmp = options;
          options = callback || {};
          callback = tmp;
      } else if (typeof options == 'undefined') {
        options = {};
      }

      return [options, callback];
    }

    /**
     * Generates a new temporary name.
     *
     * @param {Object} opts
     * @returns {String}
     * @api private
     */
    function _generateTmpName(opts) {
      if (opts.name) {
        return path.join(opts.dir || _TMP, opts.name);
      }

      // mkstemps like template
      if (opts.template) {
        return opts.template.replace(TEMPLATE_PATTERN, _randomChars(6));
      }

      // prefix and postfix
      var name = [
        opts.prefix || 'tmp-',
        process.pid,
        _randomChars(12),
        opts.postfix || ''
      ].join('');

      return path.join(opts.dir || _TMP, name);
    }

    /**
     * Gets a temporary file name.
     *
     * @param {Object} options
     * @param {Function} callback
     * @api private
     */
    function _getTmpName(options, callback) {
      var
        args = _parseArguments(options, callback),
        opts = args[0],
        cb = args[1],
        tries = opts.tries || DEFAULT_TRIES;

      if (isNaN(tries) || tries < 0)
        return cb(new Error('Invalid tries'));

      Iif (opts.template && !opts.template.match(TEMPLATE_PATTERN))
        return cb(new Error('Invalid template provided'));

      (function _getUniqueName() {
        var name = _generateTmpName(opts);

        // check whether the path exists then retry if needed
        fs.stat(name, function (err) {
          Iif (!err) {
            if (tries-- > 0) return _getUniqueName();

            return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name));
          }

          cb(null, name);
        });
      }());
    }

    /**
     * Synchronous version of _getTmpName.
     *
     * @param {Object} options
     * @returns {String}
     * @api private
     */
    function _getTmpNameSync(options) {
      var
        args = _parseArguments(options),
        opts = args[0],
        tries = opts.tries || DEFAULT_TRIES;

      if (isNaN(tries) || tries < 0)
        throw new Error('Invalid tries');

      Iif (opts.template && !opts.template.match(TEMPLATE_PATTERN))
        throw new Error('Invalid template provided');

      do {
        var name = _generateTmpName(opts);
        try {
            fs.statSync(name);
        } catch (e) {
            return name;
        }
      } while (tries-- > 0);

      throw new Error('Could not get a unique tmp filename, max tries reached');
    }

    /**
     * Creates and opens a temporary file.
     *
     * @param {Object} options
     * @param {Function} callback
     * @api public
     */
    function _createTmpFile(options, callback) {
      var
        args = _parseArguments(options, callback),
        opts = args[0],
        cb = args[1];

        opts.postfix = (_isUndefined(opts.postfix)) ? '.tmp' : opts.postfix;

      // gets a temporary filename
      _getTmpName(opts, function _tmpNameCreated(err, name) {
        if (err) return cb(err);

        // create and open the file
        fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) {
          Iif (err) return cb(err);

          cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts));
        });
      });
    }

    /**
     * Synchronous version of _createTmpFile.
     *
     * @param {Object} options
     * @returns {Object} object consists of name, fd and removeCallback
     * @api private
     */
    function _createTmpFileSync(options) {
      var
        args = _parseArguments(options),
        opts = args[0];

        opts.postfix = opts.postfix || '.tmp';

      var name = _getTmpNameSync(opts);
      var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);

      return {
        name : name,
        fd : fd,
        removeCallback : _prepareTmpFileRemoveCallback(name, fd, opts)
      };
    }

    /**
     * Removes files and folders in a directory recursively.
     *
     * @param {String} root
     * @api private
     */
    function _rmdirRecursiveSync(root) {
      var dirs = [root];

      do {
        var
          dir = dirs.pop(),
          deferred = false,
          files = fs.readdirSync(dir);

        for (var i = 0, length = files.length; i < length; i++) {
          var
            file = path.join(dir, files[i]),
            stat = fs.lstatSync(file); // lstat so we don't recurse into symlinked directories

          if (stat.isDirectory()) {
            if (!deferred) {
              deferred = true;
              dirs.push(dir);
            }
            dirs.push(file);
          } else {
            fs.unlinkSync(file);
          }
        }

        if (!deferred) {
          fs.rmdirSync(dir);
        }
      } while (dirs.length !== 0);
    }

    /**
     * Creates a temporary directory.
     *
     * @param {Object} options
     * @param {Function} callback
     * @api public
     */
    function _createTmpDir(options, callback) {
      var
        args = _parseArguments(options, callback),
        opts = args[0],
        cb = args[1];

      // gets a temporary filename
      _getTmpName(opts, function _tmpNameCreated(err, name) {
        if (err) return cb(err);

        // create the directory
        fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) {
          Iif (err) return cb(err);

          cb(null, name, _prepareTmpDirRemoveCallback(name, opts));
        });
      });
    }

    /**
     * Synchronous version of _createTmpDir.
     *
     * @param {Object} options
     * @returns {Object} object consists of name and removeCallback
     * @api private
     */
    function _createTmpDirSync(options) {
      var
        args = _parseArguments(options),
        opts = args[0];

      var name = _getTmpNameSync(opts);
      fs.mkdirSync(name, opts.mode || DIR_MODE);

      return {
        name : name,
        removeCallback : _prepareTmpDirRemoveCallback(name, opts)
      };
    }

    /**
     * Prepares the callback for removal of the temporary file.
     *
     * @param {String} name
     * @param {int} fd
     * @param {Object} opts
     * @api private
     * @returns {Function} the callback
     */
    function _prepareTmpFileRemoveCallback(name, fd, opts) {
      var removeCallback = _prepareRemoveCallback(function _removeCallback(fdPath) {
        try {
          fs.closeSync(fdPath[0]);
        }
        catch (e) {
          // under some node/windows related circumstances, a temporary file
          // may have not be created as expected or the file was already closed
          // by the user, in which case we will simply ignore the error
          if (e.errno != -_c.EBADF && e.errno != -_c.ENOENT) {
            // reraise any unanticipated error
            throw e;
          }
        }
        fs.unlinkSync(fdPath[1]);
      }, [fd, name]);

      Eif (!opts.keep) {
        _removeObjects.unshift(removeCallback);
      }

      return removeCallback;
    }

    /**
     * Prepares the callback for removal of the temporary directory.
     *
     * @param {String} name
     * @param {Object} opts
     * @returns {Function} the callback
     * @api private
     */
    function _prepareTmpDirRemoveCallback(name, opts) {
      var removeFunction = opts.unsafeCleanup ? _rmdirRecursiveSync : fs.rmdirSync.bind(fs);
      var removeCallback = _prepareRemoveCallback(removeFunction, name);

      Eif (!opts.keep) {
        _removeObjects.unshift(removeCallback);
      }

      return removeCallback;
    }

    /**
     * Creates a guarded function wrapping the removeFunction call.
     *
     * @param {Function} removeFunction
     * @param {Object} arg
     * @returns {Function}
     * @api private
     */
    function _prepareRemoveCallback(removeFunction, arg) {
      var called = false;

      return function _cleanupCallback() {
        Iif (called) return;

        var index = _removeObjects.indexOf(_cleanupCallback);
        Eif (index >= 0) {
          _removeObjects.splice(index, 1);
        }

        called = true;
        removeFunction(arg);
      };
    }

    /**
     * The garbage collector.
     *
     * @api private
     */
    function _garbageCollector() {
      if (_uncaughtException && !_gracefulCleanup) {
        return;
      }

      for (var i = 0, length = _removeObjects.length; i < length; i++) {
        try {
          _removeObjects[i].call(null);
        } catch (e) {
          // already removed?
        }
      }
    }

    function _setGracefulCleanup() {
      _gracefulCleanup = true;
    }

    var version = process.versions.node.split('.').map(function (value) {
      return parseInt(value, 10);
    });

    Iif (version[0] === 0 && (version[1] < 9 || version[1] === 9 && version[2] < 5)) {
      process.addListener('uncaughtException', function _uncaughtExceptionThrown(err) {
        _uncaughtException = true;
        _garbageCollector();

        throw err;
      });
    }

    process.addListener('exit', function _exit(code) {
      if (code) _uncaughtException = true;
      _garbageCollector();
    });

    // exporting all the needed methods
    module.exports.tmpdir = _TMP;
    module.exports.dir = _createTmpDir;
    module.exports.dirSync = _createTmpDirSync;
    module.exports.file = _createTmpFile;
    module.exports.fileSync = _createTmpFileSync;
    module.exports.tmpName = _getTmpName;
    module.exports.tmpNameSync = _getTmpNameSync;
    module.exports.setGracefulCleanup = _setGracefulCleanup;