with_tmp_dir.js 763 B

123456789101112131415161718192021222324252627
  1. const fs = require('node:fs')
  2. const fsExtra = require('fs-extra')
  3. const logger = require('@overleaf/logger')
  4. const os = require('node:os')
  5. const path = require('node:path')
  6. /**
  7. * Create a temporary directory before executing a function and cleaning up
  8. * after.
  9. *
  10. * @param {string} prefix - prefix for the temporary directory name
  11. * @param {(tmpDir: string) => Promise<void>} fn - async function to call
  12. */
  13. async function withTmpDir(prefix, fn) {
  14. const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), prefix))
  15. try {
  16. await fn(tmpDir)
  17. } finally {
  18. fsExtra.remove(tmpDir).catch(err => {
  19. if (err.code !== 'ENOENT') {
  20. logger.error({ err }, 'failed to delete temporary file')
  21. }
  22. })
  23. }
  24. }
  25. module.exports = withTmpDir