temp-file-context
v1.0.0
Published
Node functions for running code in self-cleaning temp file and directory contexts.
Maintainers
Readme
Temporary File Context
This is a zero dependency[^1] TypeScript implementation of Tamás Sallai's elegant and dependency-free solution for creating OS-agnostic, asynchronous, self-cleaning temporary file and directory contexts.[^2]
What is this for?
I got tired of implementing this pattern over and over: "Get a temporary directory name, make the directory, put a temp file in it, do stuff to the file, clean up the temporary directory"
While poking around for wrappers for temporary file operations, I found Tamás Sallai's article and it was exactly what I was looking for.
Installation
# npm
npm i temp-file-context
# pnpm
pnpm i temp-file-contextUsage
These are nonsense examples, but they show how withTempDir() and withTempFile() create a context in which you have access to a temporary directory and/or file.
The key thing to note is that once these functions exit, the temporary resources have already been destroyed; you don't need to do any additional cleanup.
Run some code within the context of a temporary directory
import { withTempDir } from "temp-file-context";
import fs from "node:fs";
withTempDir((dir) => {
let processedFileCount = 0;
for (let i = 1; i < 11; i++) {
fs.writeFileSync(`${dir}/file-${i}.txt`, `This is file ${i}`);
}
// [Do whatever else you need to do with your temporary files here]
return processedFileCount;
}).then((result) => {
console.log("Files processed", result);
});Use a temporary file
withTempFile() is very similar; it also creates a temporary directory, but instead of passing the directory name to your inner function, it passes a temporary filename within that directory.
When withTempFile() exits, it automatically destroys the temporary file and directory.
import { withTempFile } from "temp-file-context";
import fs from "node:fs";
withTempFile((filename) => {
fs.writeFileSync(filename, "This is a temporary file");
// [Do whatever you need to do with your temp file]
}).then(() => {
console.log("Finished");
});
Running Tests
# npm
npm test
#pnpm
pnpm test[^1]: Not counting development dependencies for TypeScript and testing [^2]: Sallai, T. (2020, April 7). Secure tempfiles in NodeJS without dependencies. Advanced Web Machinery. Retrieved September 23, 2026, from https://advancedweb.hu/secure-tempfiles-in-nodejs-without-dependencies/
