alinex-fs
Version:
Extension of nodes filesystem tools.
112 lines (93 loc) • 2.92 kB
JavaScript
/*
Temp Directory
==================================================
This will create a new temporary directory for you. Since Node v5.10.0 you may
also use the [`mkdtemp()`](https://nodejs.org/api/fs.html#fs_fs_mkdtemp_prefix)
method but it has a slightly changed API.
In this methods you define the temporary directory with two possible strings.
First with the directory in which to create the new one and secondly a possible
prefix before the numerical part.
Examples
-------------------------------------------------
You may get a directory back without doing anything:
``` coffee
fs = require 'alinex-fs'
fs.tempdir (err, dir) ->
console.log "Temporary directory is: " + dir
```
But don't forget to remove it if no longer needed.
*/
(function() {
var crypto, mkdirs, os, path, tempdir, tempdirSync;
path = require('path');
crypto = require('crypto');
os = require('os');
mkdirs = require('./mkdirs');
/*
@param {String} base path under which the directory should be created (use `null`
for os default settings)
@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 directory
*/
tempdir = module.exports.tempdir = function(base, prefix, cb) {
var dir;
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 + '-');
}
dir = path.join(base, prefix + crypto.randomBytes(4).readUInt32LE(0));
return mkdirs.mkdirs(dir, function(err) {
if ((err != null ? err.code : void 0) === 'EEXIST') {
return tempdir(base, prefix, cb);
}
if (err) {
return cb(err);
}
return cb(null, dir);
});
};
/*
@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
*/
tempdirSync = module.exports.tempdirSync = function(base, prefix) {
var dir, error;
if (prefix == null) {
prefix = null;
}
if (base == null) {
base = os.tmpDir();
}
if (prefix == null) {
prefix = path.basename(process.title + '-');
}
dir = path.join(base, prefix + crypto.randomBytes(4).readUInt32LE(0));
try {
mkdirs.mkdirsSync(dir);
return dir;
} catch (error1) {
error = error1;
if (error.code === 'EEXIST') {
return tempdirSync(base, prefix);
}
throw error;
}
};
}).call(this);
//# sourceMappingURL=tempdir.map