123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762 |
- /*!
- * Tmp
- *
- * Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
- *
- * MIT Licensed
- */
- /*
- * Module dependencies.
- */
- const fs = require('fs');
- const os = require('os');
- const path = require('path');
- const crypto = require('crypto');
- const _c = fs.constants && os.constants ?
- { fs: fs.constants, os: os.constants } :
- process.binding('constants');
- const rimraf = require('rimraf');
- /*
- * The working inner variables.
- */
- const
- // the random characters to choose from
- RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
- TEMPLATE_PATTERN = /XXXXXX/,
- DEFAULT_TRIES = 3,
- CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR),
- EBADF = _c.EBADF || _c.os.errno.EBADF,
- ENOENT = _c.ENOENT || _c.os.errno.ENOENT,
- DIR_MODE = 448 /* 0o700 */,
- FILE_MODE = 384 /* 0o600 */,
- EXIT = 'exit',
- SIGINT = 'SIGINT',
- // this will hold the objects need to be removed on exit
- _removeObjects = [];
- var
- _gracefulCleanup = false;
- /**
- * Random name generator based on crypto.
- * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript
- *
- * @param {number} howMany
- * @returns {string} the generated random name
- * @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
- * @returns {boolean} true if the object is undefined
- * @private
- */
- function _isUndefined(obj) {
- return typeof obj === 'undefined';
- }
- /**
- * Parses the function arguments.
- *
- * This function helps to have optional arguments.
- *
- * @param {(Options|Function)} options
- * @param {Function} callback
- * @returns {Array} parsed arguments
- * @private
- */
- function _parseArguments(options, callback) {
- /* istanbul ignore else */
- if (typeof options === 'function') {
- return [{}, options];
- }
- /* istanbul ignore else */
- if (_isUndefined(options)) {
- return [{}, callback];
- }
- return [options, callback];
- }
- /**
- * Generates a new temporary name.
- *
- * @param {Object} opts
- * @returns {string} the new random name according to opts
- * @private
- */
- function _generateTmpName(opts) {
- const tmpDir = _getTmpDir();
- // fail early on missing tmp dir
- if (isBlank(opts.dir) && isBlank(tmpDir)) {
- throw new Error('No tmp dir specified');
- }
- /* istanbul ignore else */
- if (!isBlank(opts.name)) {
- return path.join(opts.dir || tmpDir, opts.name);
- }
- // mkstemps like template
- // opts.template has already been guarded in tmpName() below
- /* istanbul ignore else */
- if (opts.template) {
- var template = opts.template;
- // make sure that we prepend the tmp path if none was given
- /* istanbul ignore else */
- if (path.basename(template) === template)
- template = path.join(opts.dir || tmpDir, template);
- return template.replace(TEMPLATE_PATTERN, _randomChars(6));
- }
- // prefix and postfix
- const name = [
- (isBlank(opts.prefix) ? 'tmp-' : opts.prefix),
- process.pid,
- _randomChars(12),
- (opts.postfix ? opts.postfix : '')
- ].join('');
- return path.join(opts.dir || tmpDir, name);
- }
- /**
- * Gets a temporary file name.
- *
- * @param {(Options|tmpNameCallback)} options options or callback
- * @param {?tmpNameCallback} callback the callback function
- */
- function tmpName(options, callback) {
- var
- args = _parseArguments(options, callback),
- opts = args[0],
- cb = args[1],
- tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES;
- /* istanbul ignore else */
- if (isNaN(tries) || tries < 0)
- return cb(new Error('Invalid tries'));
- /* istanbul ignore else */
- if (opts.template && !opts.template.match(TEMPLATE_PATTERN))
- return cb(new Error('Invalid template provided'));
- (function _getUniqueName() {
- try {
- const name = _generateTmpName(opts);
- // check whether the path exists then retry if needed
- fs.stat(name, function (err) {
- /* istanbul ignore else */
- if (!err) {
- /* istanbul ignore else */
- if (tries-- > 0) return _getUniqueName();
- return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name));
- }
- cb(null, name);
- });
- } catch (err) {
- cb(err);
- }
- }());
- }
- /**
- * Synchronous version of tmpName.
- *
- * @param {Object} options
- * @returns {string} the generated random name
- * @throws {Error} if the options are invalid or could not generate a filename
- */
- function tmpNameSync(options) {
- var
- args = _parseArguments(options),
- opts = args[0],
- tries = !isBlank(opts.name) ? 1 : opts.tries || DEFAULT_TRIES;
- /* istanbul ignore else */
- if (isNaN(tries) || tries < 0)
- throw new Error('Invalid tries');
- /* istanbul ignore else */
- if (opts.template && !opts.template.match(TEMPLATE_PATTERN))
- throw new Error('Invalid template provided');
- do {
- const 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 {(Options|fileCallback)} options the config options or the callback function
- * @param {?fileCallback} callback
- */
- function file(options, callback) {
- var
- args = _parseArguments(options, callback),
- opts = args[0],
- cb = args[1];
- // gets a temporary filename
- tmpName(opts, function _tmpNameCreated(err, name) {
- /* istanbul ignore else */
- if (err) return cb(err);
- // create and open the file
- fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) {
- /* istanbul ignore else */
- if (err) return cb(err);
- if (opts.discardDescriptor) {
- return fs.close(fd, function _discardCallback(err) {
- /* istanbul ignore else */
- if (err) {
- // Low probability, and the file exists, so this could be
- // ignored. If it isn't we certainly need to unlink the
- // file, and if that fails too its error is more
- // important.
- try {
- fs.unlinkSync(name);
- } catch (e) {
- if (!isENOENT(e)) {
- err = e;
- }
- }
- return cb(err);
- }
- cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts));
- });
- }
- /* istanbul ignore else */
- if (opts.detachDescriptor) {
- return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts));
- }
- cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts));
- });
- });
- }
- /**
- * Synchronous version of file.
- *
- * @param {Options} options
- * @returns {FileSyncObject} object consists of name, fd and removeCallback
- * @throws {Error} if cannot create a file
- */
- function fileSync(options) {
- var
- args = _parseArguments(options),
- opts = args[0];
- const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
- const name = tmpNameSync(opts);
- var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
- /* istanbul ignore else */
- if (opts.discardDescriptor) {
- fs.closeSync(fd);
- fd = undefined;
- }
- return {
- name: name,
- fd: fd,
- removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts)
- };
- }
- /**
- * Creates a temporary directory.
- *
- * @param {(Options|dirCallback)} options the options or the callback function
- * @param {?dirCallback} callback
- */
- function dir(options, callback) {
- var
- args = _parseArguments(options, callback),
- opts = args[0],
- cb = args[1];
- // gets a temporary filename
- tmpName(opts, function _tmpNameCreated(err, name) {
- /* istanbul ignore else */
- if (err) return cb(err);
- // create the directory
- fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) {
- /* istanbul ignore else */
- if (err) return cb(err);
- cb(null, name, _prepareTmpDirRemoveCallback(name, opts));
- });
- });
- }
- /**
- * Synchronous version of dir.
- *
- * @param {Options} options
- * @returns {DirSyncObject} object consists of name and removeCallback
- * @throws {Error} if it cannot create a directory
- */
- function dirSync(options) {
- var
- args = _parseArguments(options),
- opts = args[0];
- const name = tmpNameSync(opts);
- fs.mkdirSync(name, opts.mode || DIR_MODE);
- return {
- name: name,
- removeCallback: _prepareTmpDirRemoveCallback(name, opts)
- };
- }
- /**
- * Removes files asynchronously.
- *
- * @param {Object} fdPath
- * @param {Function} next
- * @private
- */
- function _removeFileAsync(fdPath, next) {
- const _handler = function (err) {
- if (err && !isENOENT(err)) {
- // reraise any unanticipated error
- return next(err);
- }
- next();
- }
- if (0 <= fdPath[0])
- fs.close(fdPath[0], function (err) {
- fs.unlink(fdPath[1], _handler);
- });
- else fs.unlink(fdPath[1], _handler);
- }
- /**
- * Removes files synchronously.
- *
- * @param {Object} fdPath
- * @private
- */
- function _removeFileSync(fdPath) {
- try {
- if (0 <= fdPath[0]) fs.closeSync(fdPath[0]);
- } catch (e) {
- // reraise any unanticipated error
- if (!isEBADF(e) && !isENOENT(e)) throw e;
- } finally {
- try {
- fs.unlinkSync(fdPath[1]);
- }
- catch (e) {
- // reraise any unanticipated error
- if (!isENOENT(e)) throw e;
- }
- }
- }
- /**
- * Prepares the callback for removal of the temporary file.
- *
- * @param {string} name the path of the file
- * @param {number} fd file descriptor
- * @param {Object} opts
- * @returns {fileCallback}
- * @private
- */
- function _prepareTmpFileRemoveCallback(name, fd, opts) {
- const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name]);
- const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], removeCallbackSync);
- if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
- return removeCallback;
- }
- /**
- * Simple wrapper for rimraf.
- *
- * @param {string} dirPath
- * @param {Function} next
- * @private
- */
- function _rimrafRemoveDirWrapper(dirPath, next) {
- rimraf(dirPath, next);
- }
- /**
- * Simple wrapper for rimraf.sync.
- *
- * @param {string} dirPath
- * @private
- */
- function _rimrafRemoveDirSyncWrapper(dirPath, next) {
- try {
- return next(null, rimraf.sync(dirPath));
- } catch (err) {
- return next(err);
- }
- }
- /**
- * Prepares the callback for removal of the temporary directory.
- *
- * @param {string} name
- * @param {Object} opts
- * @returns {Function} the callback
- * @private
- */
- function _prepareTmpDirRemoveCallback(name, opts) {
- const removeFunction = opts.unsafeCleanup ? _rimrafRemoveDirWrapper : fs.rmdir.bind(fs);
- const removeFunctionSync = opts.unsafeCleanup ? _rimrafRemoveDirSyncWrapper : fs.rmdirSync.bind(fs);
- const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name);
- const removeCallback = _prepareRemoveCallback(removeFunction, name, removeCallbackSync);
- if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
- return removeCallback;
- }
- /**
- * Creates a guarded function wrapping the removeFunction call.
- *
- * @param {Function} removeFunction
- * @param {Object} arg
- * @returns {Function}
- * @private
- */
- function _prepareRemoveCallback(removeFunction, arg, cleanupCallbackSync) {
- var called = false;
- return function _cleanupCallback(next) {
- next = next || function () {};
- if (!called) {
- const toRemove = cleanupCallbackSync || _cleanupCallback;
- const index = _removeObjects.indexOf(toRemove);
- /* istanbul ignore else */
- if (index >= 0) _removeObjects.splice(index, 1);
- called = true;
- // sync?
- if (removeFunction.length === 1) {
- try {
- removeFunction(arg);
- return next(null);
- }
- catch (err) {
- // if no next is provided and since we are
- // in silent cleanup mode on process exit,
- // we will ignore the error
- return next(err);
- }
- } else return removeFunction(arg, next);
- } else return next(new Error('cleanup callback has already been called'));
- };
- }
- /**
- * The garbage collector.
- *
- * @private
- */
- function _garbageCollector() {
- /* istanbul ignore else */
- if (!_gracefulCleanup) return;
- // the function being called removes itself from _removeObjects,
- // loop until _removeObjects is empty
- while (_removeObjects.length) {
- try {
- _removeObjects[0]();
- } catch (e) {
- // already removed?
- }
- }
- }
- /**
- * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows.
- */
- function isEBADF(error) {
- return isExpectedError(error, -EBADF, 'EBADF');
- }
- /**
- * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows.
- */
- function isENOENT(error) {
- return isExpectedError(error, -ENOENT, 'ENOENT');
- }
- /**
- * Helper to determine whether the expected error code matches the actual code and errno,
- * which will differ between the supported node versions.
- *
- * - Node >= 7.0:
- * error.code {string}
- * error.errno {string|number} any numerical value will be negated
- *
- * - Node >= 6.0 < 7.0:
- * error.code {string}
- * error.errno {number} negated
- *
- * - Node >= 4.0 < 6.0: introduces SystemError
- * error.code {string}
- * error.errno {number} negated
- *
- * - Node >= 0.10 < 4.0:
- * error.code {number} negated
- * error.errno n/a
- */
- function isExpectedError(error, code, errno) {
- return error.code === code || error.code === errno;
- }
- /**
- * Helper which determines whether a string s is blank, that is undefined, or empty or null.
- *
- * @private
- * @param {string} s
- * @returns {Boolean} true whether the string s is blank, false otherwise
- */
- function isBlank(s) {
- return s === null || s === undefined || !s.trim();
- }
- /**
- * Sets the graceful cleanup.
- */
- function setGracefulCleanup() {
- _gracefulCleanup = true;
- }
- /**
- * Returns the currently configured tmp dir from os.tmpdir().
- *
- * @private
- * @returns {string} the currently configured tmp dir
- */
- function _getTmpDir() {
- return os.tmpdir();
- }
- /**
- * If there are multiple different versions of tmp in place, make sure that
- * we recognize the old listeners.
- *
- * @param {Function} listener
- * @private
- * @returns {Boolean} true whether listener is a legacy listener
- */
- function _is_legacy_listener(listener) {
- return (listener.name === '_exit' || listener.name === '_uncaughtExceptionThrown')
- && listener.toString().indexOf('_garbageCollector();') > -1;
- }
- /**
- * Safely install SIGINT listener.
- *
- * NOTE: this will only work on OSX and Linux.
- *
- * @private
- */
- function _safely_install_sigint_listener() {
- const listeners = process.listeners(SIGINT);
- const existingListeners = [];
- for (let i = 0, length = listeners.length; i < length; i++) {
- const lstnr = listeners[i];
- /* istanbul ignore else */
- if (lstnr.name === '_tmp$sigint_listener') {
- existingListeners.push(lstnr);
- process.removeListener(SIGINT, lstnr);
- }
- }
- process.on(SIGINT, function _tmp$sigint_listener(doExit) {
- for (let i = 0, length = existingListeners.length; i < length; i++) {
- // let the existing listener do the garbage collection (e.g. jest sandbox)
- try {
- existingListeners[i](false);
- } catch (err) {
- // ignore
- }
- }
- try {
- // force the garbage collector even it is called again in the exit listener
- _garbageCollector();
- } finally {
- if (!!doExit) {
- process.exit(0);
- }
- }
- });
- }
- /**
- * Safely install process exit listener.
- *
- * @private
- */
- function _safely_install_exit_listener() {
- const listeners = process.listeners(EXIT);
- // collect any existing listeners
- const existingListeners = [];
- for (let i = 0, length = listeners.length; i < length; i++) {
- const lstnr = listeners[i];
- /* istanbul ignore else */
- // TODO: remove support for legacy listeners once release 1.0.0 is out
- if (lstnr.name === '_tmp$safe_listener' || _is_legacy_listener(lstnr)) {
- // we must forget about the uncaughtException listener, hopefully it is ours
- if (lstnr.name !== '_uncaughtExceptionThrown') {
- existingListeners.push(lstnr);
- }
- process.removeListener(EXIT, lstnr);
- }
- }
- // TODO: what was the data parameter good for?
- process.addListener(EXIT, function _tmp$safe_listener(data) {
- for (let i = 0, length = existingListeners.length; i < length; i++) {
- // let the existing listener do the garbage collection (e.g. jest sandbox)
- try {
- existingListeners[i](data);
- } catch (err) {
- // ignore
- }
- }
- _garbageCollector();
- });
- }
- _safely_install_exit_listener();
- _safely_install_sigint_listener();
- /**
- * Configuration options.
- *
- * @typedef {Object} Options
- * @property {?number} tries the number of tries before give up the name generation
- * @property {?string} template the "mkstemp" like filename template
- * @property {?string} name fix name
- * @property {?string} dir the tmp directory to use
- * @property {?string} prefix prefix for the generated name
- * @property {?string} postfix postfix for the generated name
- * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty
- */
- /**
- * @typedef {Object} FileSyncObject
- * @property {string} name the name of the file
- * @property {string} fd the file descriptor
- * @property {fileCallback} removeCallback the callback function to remove the file
- */
- /**
- * @typedef {Object} DirSyncObject
- * @property {string} name the name of the directory
- * @property {fileCallback} removeCallback the callback function to remove the directory
- */
- /**
- * @callback tmpNameCallback
- * @param {?Error} err the error object if anything goes wrong
- * @param {string} name the temporary file name
- */
- /**
- * @callback fileCallback
- * @param {?Error} err the error object if anything goes wrong
- * @param {string} name the temporary file name
- * @param {number} fd the file descriptor
- * @param {cleanupCallback} fn the cleanup callback function
- */
- /**
- * @callback dirCallback
- * @param {?Error} err the error object if anything goes wrong
- * @param {string} name the temporary file name
- * @param {cleanupCallback} fn the cleanup callback function
- */
- /**
- * Removes the temporary created file or directory.
- *
- * @callback cleanupCallback
- * @param {simpleCallback} [next] function to call after entry was removed
- */
- /**
- * Callback function for function composition.
- * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57}
- *
- * @callback simpleCallback
- */
- // exporting all the needed methods
- // evaluate os.tmpdir() lazily, mainly for simplifying testing but it also will
- // allow users to reconfigure the temporary directory
- Object.defineProperty(module.exports, 'tmpdir', {
- enumerable: true,
- configurable: false,
- get: function () {
- return _getTmpDir();
- }
- });
- module.exports.dir = dir;
- module.exports.dirSync = dirSync;
- module.exports.file = file;
- module.exports.fileSync = fileSync;
- module.exports.tmpName = tmpName;
- module.exports.tmpNameSync = tmpNameSync;
- module.exports.setGracefulCleanup = setGracefulCleanup;
|