with-temp-dir.js 900 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. const { join, sep } = require('path')
  2. const getOptions = require('./common/get-options.js')
  3. const { mkdir, mkdtemp, rm } = require('fs/promises')
  4. // create a temp directory, ensure its permissions match its parent, then call
  5. // the supplied function passing it the path to the directory. clean up after
  6. // the function finishes, whether it throws or not
  7. const withTempDir = async (root, fn, opts) => {
  8. const options = getOptions(opts, {
  9. copy: ['tmpPrefix'],
  10. })
  11. // create the directory
  12. await mkdir(root, { recursive: true })
  13. const target = await mkdtemp(join(`${root}${sep}`, options.tmpPrefix || ''))
  14. let err
  15. let result
  16. try {
  17. result = await fn(target)
  18. } catch (_err) {
  19. err = _err
  20. }
  21. try {
  22. await rm(target, { force: true, recursive: true })
  23. } catch {
  24. // ignore errors
  25. }
  26. if (err) {
  27. throw err
  28. }
  29. return result
  30. }
  31. module.exports = withTempDir