with-temp-dir.js 1009 B

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