index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. const { promisify } = require("util");
  3. const tmp = require("tmp");
  4. // file
  5. module.exports.fileSync = tmp.fileSync;
  6. const fileWithOptions = promisify((options, cb) =>
  7. tmp.file(options, (err, path, fd, cleanup) =>
  8. err ? cb(err) : cb(undefined, { path, fd, cleanup: promisify(cleanup) })
  9. )
  10. );
  11. module.exports.file = async (options) => fileWithOptions(options);
  12. module.exports.withFile = async function withFile(fn, options) {
  13. const { path, fd, cleanup } = await module.exports.file(options);
  14. try {
  15. return await fn({ path, fd });
  16. } finally {
  17. await cleanup();
  18. }
  19. };
  20. // directory
  21. module.exports.dirSync = tmp.dirSync;
  22. const dirWithOptions = promisify((options, cb) =>
  23. tmp.dir(options, (err, path, cleanup) =>
  24. err ? cb(err) : cb(undefined, { path, cleanup: promisify(cleanup) })
  25. )
  26. );
  27. module.exports.dir = async (options) => dirWithOptions(options);
  28. module.exports.withDir = async function withDir(fn, options) {
  29. const { path, cleanup } = await module.exports.dir(options);
  30. try {
  31. return await fn({ path });
  32. } finally {
  33. await cleanup();
  34. }
  35. };
  36. // name generation
  37. module.exports.tmpNameSync = tmp.tmpNameSync;
  38. module.exports.tmpName = promisify(tmp.tmpName);
  39. module.exports.tmpdir = tmp.tmpdir;
  40. module.exports.setGracefulCleanup = tmp.setGracefulCleanup;