Skip to content

Instantly share code, notes, and snippets.

@tekerson
Created January 10, 2017 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tekerson/9256607f9c7ec1f7c98fcac9dc572319 to your computer and use it in GitHub Desktop.
Save tekerson/9256607f9c7ec1f7c98fcac9dc572319 to your computer and use it in GitHub Desktop.
const tmp = require('tmp')
/**
* Create a temporary directory and ensure that it is cleaned up after the handler completes
* @sig (tmpDir: String -> a) -> Promise a
*/
exports.withTempDirectory = (handler) => new Promise((resolve, reject) => {
tmp.dir({ unsafeCleanup: true }, (err, tmpDir, cleanup) => {
if (err) {
reject(err)
return
}
const result = handler(tmpDir)
.then(
(result) => {
cleanup()
return result // propagate success
},
(error) => {
cleanup()
throw error // propagate failure
})
resolve(result)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment