Get a unique temp file - Node.js File

Node.js examples for File:Text File

Description

Get a unique temp file

Demo Code


/**//from w ww .j a  v  a2s  . c  o  m
 * Get a unique temp file
 *
 * @returns {string} unique-ish path to file in given directory.
 * @throws when it cannot create a temp file in the specified directory
 */
function getTempFile(prefix, dir, extension) {
    if (dir === void 0) { dir = ''; }
    if (extension === void 0) { extension = '.tmp.txt'; }
    prefix = (prefix ? prefix + '-' : '');
    var attempts = 100;
    do {
        var name = prefix + getRandomHex(8) + extension;
        var dest = path.join(dir, name);
        if (!fs.existsSync(dest)) {
            return dest;
        }
        attempts--;
    } while (attempts > 0);
    throw 'Cannot create temp file in ' + dir;
}

Related Tutorials