temp.js 6.4 KB

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