temp.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. /* IMPORT */
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. const path = require("path");
  5. const consts_1 = require("../consts");
  6. const fs_1 = require("./fs");
  7. /* TEMP */
  8. //TODO: Maybe publish this as a standalone package
  9. const Temp = {
  10. store: {},
  11. create: (filePath) => {
  12. const randomness = `000000${Math.floor(Math.random() * 16777215).toString(16)}`.slice(-6), // 6 random-enough hex characters
  13. timestamp = Date.now().toString().slice(-10), // 10 precise timestamp digits
  14. prefix = 'tmp-', suffix = `.${prefix}${timestamp}${randomness}`, tempPath = `${filePath}${suffix}`;
  15. return tempPath;
  16. },
  17. get: (filePath, creator, purge = true) => {
  18. const tempPath = Temp.truncate(creator(filePath));
  19. if (tempPath in Temp.store)
  20. return Temp.get(filePath, creator, purge); // Collision found, try again
  21. Temp.store[tempPath] = purge;
  22. const disposer = () => delete Temp.store[tempPath];
  23. return [tempPath, disposer];
  24. },
  25. purge: (filePath) => {
  26. if (!Temp.store[filePath])
  27. return;
  28. delete Temp.store[filePath];
  29. fs_1.default.unlinkAttempt(filePath);
  30. },
  31. purgeSync: (filePath) => {
  32. if (!Temp.store[filePath])
  33. return;
  34. delete Temp.store[filePath];
  35. fs_1.default.unlinkSyncAttempt(filePath);
  36. },
  37. purgeSyncAll: () => {
  38. for (const filePath in Temp.store) {
  39. Temp.purgeSync(filePath);
  40. }
  41. },
  42. truncate: (filePath) => {
  43. const basename = path.basename(filePath);
  44. if (basename.length <= consts_1.LIMIT_BASENAME_LENGTH)
  45. return filePath; //FIXME: Rough and quick attempt at detecting ok lengths
  46. const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename);
  47. if (!truncable)
  48. return filePath; //FIXME: No truncable part detected, can't really do much without also changing the parent path, which is unsafe, hoping for the best here
  49. const truncationLength = basename.length - consts_1.LIMIT_BASENAME_LENGTH;
  50. return `${filePath.slice(0, -basename.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`; //FIXME: The truncable part might be shorter than needed here
  51. }
  52. };
  53. /* INIT */
  54. process.on('exit', Temp.purgeSyncAll); // Ensuring purgeable temp files are purged on exit
  55. /* EXPORT */
  56. exports.default = Temp;