UNPKG

alinex-fs

Version:

Extension of nodes filesystem tools.

108 lines (90 loc) 2.75 kB
/* Temp File ================================================= This will create a new temporary file for you. Like in [`tempdir()`](tempdir.coffee) you may give a specific path and prefix before the numeral file part. Examples ------------------------------------------------- You may get a file back without doing anything: ``` coffee fs = require 'alinex-fs' fs.tempfile (err, dir) -> console.log "Temporary file is: " + dir ``` But don't forget to remove it if no longer needed. */ (function() { var crypto, fs, os, path, tempfile, tempfileSync; fs = require('fs'); path = require('path'); crypto = require('crypto'); os = require('os'); /* @param {String} base path under which the directory should be created (use `null` to make it in the os default directory) @param {String} [prefix=process title] to use before numerical part @param {function(<Error>, <String>)} cb callback with `Error` or the path to the newly created file */ tempfile = module.exports.tempfile = function(base, prefix, cb) { var file; if (prefix == null) { prefix = null; } if ((cb == null) && typeof prefix === 'function') { cb = prefix; prefix = null; } if ((cb == null) && typeof base === 'function') { cb = base; base = null; } if (base == null) { base = os.tmpDir(); } if (prefix == null) { prefix = path.basename(process.title + '-'); } file = path.join(base, prefix + crypto.randomBytes(4).readUInt32LE(0)); return fs.open(file, 'wx', function(err, fd) { if ((err != null ? err.code : void 0) === 'EEXIST') { return tempfile(base, prefix, cb); } if (err) { return cb(err); } return fs.close(fd, function() { return cb(null, file); }); }); }; /* @param {String} {base=os settings} path under which the directory should be created @param {String} [prefix=process title] to use before numerical part @return {String} the path to the newly created directory @throws {Error} if something went wrong */ tempfileSync = module.exports.tempfileSync = function(base, prefix) { var error, file; if (prefix == null) { prefix = null; } if (base == null) { base = os.tmpDir(); } if (prefix == null) { prefix = path.basename(process.title + '-'); } file = path.join(base, prefix + crypto.randomBytes(4).readUInt32LE(0)); try { fs.closeSync(fs.openSync(file, 'wx')); return file; } catch (error1) { error = error1; if (error.code === 'EEXIST') { return tempfileSync(base, prefix); } throw error; } }; }).call(this); //# sourceMappingURL=tempfile.map