node/deps/npm/node_modules/@npmcli/fs/lib/with-temp-dir.js
npm CLI robot 96601cc759
deps: upgrade npm to 8.16.0
PR-URL: https://github.com/nodejs/node/pull/44119
Reviewed-By: Ruy Adorno <ruyadorno@google.com>
Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com>
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Myles Borins <myles.borins@gmail.com>
2022-08-05 04:23:58 +00:00

40 lines
997 B
JavaScript

const { join, sep } = require('path')
const getOptions = require('./common/get-options.js')
const mkdir = require('./mkdir.js')
const mkdtemp = require('./mkdtemp.js')
const rm = require('./rm/index.js')
// create a temp directory, ensure its permissions match its parent, then call
// the supplied function passing it the path to the directory. clean up after
// the function finishes, whether it throws or not
const withTempDir = async (root, fn, opts) => {
const options = getOptions(opts, {
copy: ['tmpPrefix'],
})
// create the directory, and fix its ownership
await mkdir(root, { recursive: true, owner: 'inherit' })
const target = await mkdtemp(join(`${root}${sep}`, options.tmpPrefix || ''), { owner: 'inherit' })
let err
let result
try {
result = await fn(target)
} catch (_err) {
err = _err
}
try {
await rm(target, { force: true, recursive: true })
} catch {}
if (err) {
throw err
}
return result
}
module.exports = withTempDir