tmpfile.js 1.1 KB

12345678910111213141516171819202122232425
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.withTempFile = void 0;
  7. const promises_1 = __importDefault(require("fs/promises"));
  8. const os_1 = __importDefault(require("os"));
  9. const path_1 = __importDefault(require("path"));
  10. // Invokes the given handler with the path to a temporary file. The file
  11. // is deleted after the handler returns.
  12. const withTempFile = async (handler) => withTempDir(async (dir) => handler(path_1.default.join(dir, 'tempfile')));
  13. exports.withTempFile = withTempFile;
  14. // Invokes the given handler with a temporary directory. The directory is
  15. // deleted after the handler returns.
  16. const withTempDir = async (handler) => {
  17. const tmpDir = await promises_1.default.realpath(os_1.default.tmpdir());
  18. const dir = await promises_1.default.mkdtemp(tmpDir + path_1.default.sep);
  19. try {
  20. return await handler(dir);
  21. }
  22. finally {
  23. await promises_1.default.rm(dir, { force: true, recursive: true, maxRetries: 3 });
  24. }
  25. };