temp.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. var fs = require('fs'),
  2. path = require('path'),
  3. cnst = require('constants');
  4. var rimraf = require('rimraf'),
  5. os = require('os'),
  6. rimrafSync = rimraf.sync;
  7. /* HELPERS */
  8. var dir = path.resolve(os.tmpdir());
  9. var RDWR_EXCL = cnst.O_CREAT | cnst.O_TRUNC | cnst.O_RDWR | cnst.O_EXCL;
  10. var promisify = function(callback) {
  11. if (typeof callback === 'function') {
  12. return [undefined, callback];
  13. }
  14. var promiseCallback;
  15. var promise = new Promise(function(resolve, reject) {
  16. promiseCallback = function() {
  17. var args = Array.from(arguments);
  18. var err = args.shift();
  19. process.nextTick(function() {
  20. if (err) {
  21. reject(err);
  22. } else if (args.length === 1) {
  23. resolve(args[0]);
  24. } else {
  25. resolve(args);
  26. }
  27. });
  28. };
  29. });
  30. return [promise, promiseCallback];
  31. };
  32. var generateName = function(rawAffixes, defaultPrefix) {
  33. var affixes = parseAffixes(rawAffixes, defaultPrefix);
  34. var now = new Date();
  35. var name = [affixes.prefix,
  36. now.getFullYear(), now.getMonth(), now.getDate(),
  37. '-',
  38. process.pid,
  39. '-',
  40. (Math.random() * 0x100000000 + 1).toString(36),
  41. affixes.suffix].join('');
  42. return path.join(affixes.dir || dir, name);
  43. };
  44. var parseAffixes = function(rawAffixes, defaultPrefix) {
  45. var affixes = {prefix: null, suffix: null};
  46. if(rawAffixes) {
  47. switch (typeof(rawAffixes)) {
  48. case 'string':
  49. affixes.prefix = rawAffixes;
  50. break;
  51. case 'object':
  52. affixes = rawAffixes;
  53. break;
  54. default:
  55. throw new Error("Unknown affix declaration: " + affixes);
  56. }
  57. } else {
  58. affixes.prefix = defaultPrefix;
  59. }
  60. return affixes;
  61. };
  62. /* -------------------------------------------------------------------------
  63. * Don't forget to call track() if you want file tracking and exit handlers!
  64. * -------------------------------------------------------------------------
  65. * When any temp file or directory is created, it is added to filesToDelete
  66. * or dirsToDelete. The first time any temp file is created, a listener is
  67. * added to remove all temp files and directories at exit.
  68. */
  69. var tracking = false;
  70. var track = function(value) {
  71. tracking = (value !== false);
  72. return module.exports; // chainable
  73. };
  74. var exitListenerAttached = false;
  75. var filesToDelete = [];
  76. var dirsToDelete = [];
  77. function deleteFileOnExit(filePath) {
  78. if (!tracking) return false;
  79. attachExitListener();
  80. filesToDelete.push(filePath);
  81. }
  82. function deleteDirOnExit(dirPath) {
  83. if (!tracking) return false;
  84. attachExitListener();
  85. dirsToDelete.push(dirPath);
  86. }
  87. function attachExitListener() {
  88. if (!tracking) return false;
  89. if (!exitListenerAttached) {
  90. process.addListener('exit', cleanupSync);
  91. exitListenerAttached = true;
  92. }
  93. }
  94. function cleanupFilesSync() {
  95. if (!tracking) {
  96. return false;
  97. }
  98. var count = 0;
  99. var toDelete;
  100. while ((toDelete = filesToDelete.shift()) !== undefined) {
  101. rimrafSync(toDelete);
  102. count++;
  103. }
  104. return count;
  105. }
  106. function cleanupFiles(callback) {
  107. var p = promisify(callback);
  108. var promise = p[0];
  109. callback = p[1];
  110. if (!tracking) {
  111. callback(new Error("not tracking"));
  112. return promise;
  113. }
  114. var count = 0;
  115. var left = filesToDelete.length;
  116. if (!left) {
  117. callback(null, count);
  118. return promise;
  119. }
  120. var toDelete;
  121. var rimrafCallback = function(err) {
  122. if (!left) {
  123. // Prevent processing if aborted
  124. return;
  125. }
  126. if (err) {
  127. // This shouldn't happen; pass error to callback and abort
  128. // processing
  129. callback(err);
  130. left = 0;
  131. return;
  132. } else {
  133. count++;
  134. }
  135. left--;
  136. if (!left) {
  137. callback(null, count);
  138. }
  139. };
  140. while ((toDelete = filesToDelete.shift()) !== undefined) {
  141. rimraf(toDelete, rimrafCallback);
  142. }
  143. return promise;
  144. }
  145. function cleanupDirsSync() {
  146. if (!tracking) {
  147. return false;
  148. }
  149. var count = 0;
  150. var toDelete;
  151. while ((toDelete = dirsToDelete.shift()) !== undefined) {
  152. rimrafSync(toDelete);
  153. count++;
  154. }
  155. return count;
  156. }
  157. function cleanupDirs(callback) {
  158. var p = promisify(callback);
  159. var promise = p[0];
  160. callback = p[1];
  161. if (!tracking) {
  162. callback(new Error("not tracking"));
  163. return promise;
  164. }
  165. var count = 0;
  166. var left = dirsToDelete.length;
  167. if (!left) {
  168. callback(null, count);
  169. return promise;
  170. }
  171. var toDelete;
  172. var rimrafCallback = function (err) {
  173. if (!left) {
  174. // Prevent processing if aborted
  175. return;
  176. }
  177. if (err) {
  178. // rimraf handles most "normal" errors; pass the error to the
  179. // callback and abort processing
  180. callback(err, count);
  181. left = 0;
  182. return;
  183. } else {
  184. count++;
  185. }
  186. left--;
  187. if (!left) {
  188. callback(null, count);
  189. }
  190. };
  191. while ((toDelete = dirsToDelete.shift()) !== undefined) {
  192. rimraf(toDelete, rimrafCallback);
  193. }
  194. return promise;
  195. }
  196. function cleanupSync() {
  197. if (!tracking) {
  198. return false;
  199. }
  200. var fileCount = cleanupFilesSync();
  201. var dirCount = cleanupDirsSync();
  202. return {files: fileCount, dirs: dirCount};
  203. }
  204. function cleanup(callback) {
  205. var p = promisify(callback);
  206. var promise = p[0];
  207. callback = p[1];
  208. if (!tracking) {
  209. callback(new Error("not tracking"));
  210. return promise;
  211. }
  212. cleanupFiles(function(fileErr, fileCount) {
  213. if (fileErr) {
  214. callback(fileErr, {files: fileCount});
  215. } else {
  216. cleanupDirs(function(dirErr, dirCount) {
  217. callback(dirErr, {files: fileCount, dirs: dirCount});
  218. });
  219. }
  220. });
  221. return promise;
  222. }
  223. /* DIRECTORIES */
  224. function mkdir(affixes, callback) {
  225. var p = promisify(callback);
  226. var promise = p[0];
  227. callback = p[1];
  228. var dirPath = generateName(affixes, 'd-');
  229. fs.mkdir(dirPath, parseInt('0700', 8), function(err) {
  230. if (!err) {
  231. deleteDirOnExit(dirPath);
  232. }
  233. callback(err, dirPath);
  234. });
  235. return promise;
  236. }
  237. function mkdirSync(affixes) {
  238. var dirPath = generateName(affixes, 'd-');
  239. fs.mkdirSync(dirPath, parseInt('0700', 8));
  240. deleteDirOnExit(dirPath);
  241. return dirPath;
  242. }
  243. /* FILES */
  244. function open(affixes, callback) {
  245. var p = promisify(callback);
  246. var promise = p[0];
  247. callback = p[1];
  248. var filePath = generateName(affixes, 'f-');
  249. fs.open(filePath, RDWR_EXCL, parseInt('0600', 8), function(err, fd) {
  250. if (!err) {
  251. deleteFileOnExit(filePath);
  252. }
  253. callback(err, {path: filePath, fd: fd});
  254. });
  255. return promise;
  256. }
  257. function openSync(affixes) {
  258. var filePath = generateName(affixes, 'f-');
  259. var fd = fs.openSync(filePath, RDWR_EXCL, parseInt('0600', 8));
  260. deleteFileOnExit(filePath);
  261. return {path: filePath, fd: fd};
  262. }
  263. function createWriteStream(affixes) {
  264. var filePath = generateName(affixes, 's-');
  265. var stream = fs.createWriteStream(filePath, {flags: RDWR_EXCL, mode: parseInt('0600', 8)});
  266. deleteFileOnExit(filePath);
  267. return stream;
  268. }
  269. /* EXPORTS */
  270. // Settings
  271. exports.dir = dir;
  272. exports.track = track;
  273. // Functions
  274. exports.mkdir = mkdir;
  275. exports.mkdirSync = mkdirSync;
  276. exports.open = open;
  277. exports.openSync = openSync;
  278. exports.path = generateName;
  279. exports.cleanup = cleanup;
  280. exports.cleanupSync = cleanupSync;
  281. exports.createWriteStream = createWriteStream;