Skip to content

withTempDir

Creates a fresh temporary directory under the OS temp root, runs fn with its path, and always removes it (recursively) afterward — including when fn throws.

Available since v3.1.1

import { withTempDir } from '@helpers4/node';
// or, from the all-in-one package (same code, one install):
import { withTempDir } from 'helpers4/node';
withTempDir<T>(prefix: string, fn: function): Promise<T>
ParameterTypeDescription
prefixstringPrepended to the generated directory name, to make it identifiable
fnfunctionReceives the temp directory’s absolute path; its (possibly synchronous) return value is returned

Promise<T> — Whatever fn returns or resolves to

Do work in a scratch directory that always gets cleaned up

Section titled “Do work in a scratch directory that always gets cleaned up”

The directory is removed once fn resolves, even if fn throws.

await withTempDir('my-tool', async (dir) => {
  await writeFile(`${dir}/output.txt`, 'data');
  return readFile(`${dir}/output.txt`, 'utf-8');
});
// => 'data' (the directory no longer exists once this resolves)

View source on GitHub