Temporary files
suggest changePrograms often need a scratch place on disk: an upload being processed, an intermediate result handed to another tool, a test fixture, a file that is being written before it replaces the real one.
Node.js has no single "temp file" function, but the building blocks are all in core:
| Task | API |
|---|---|
| Where temp files go | os.tmpdir() |
| Create a unique directory | fs.mkdtemp(), fs.mkdtempSync() |
| Create a directory that removes itself | fs.mkdtempDisposable(), fs.mkdtempDisposableSync() (Node.js 24.4+) |
| Create a unique file safely | fs.open(path, 'wx', 0o600) with a random name |
| Remove a directory tree | fs.rm(dir, { recursive: true, force: true }) |
The examples are ES modules (save them as .mjs) and were run with Node.js 24 on Linux.
Finding the temp directory
os.tmpdir() returns the operating system's directory for temporary files:
import os from 'node:os';
console.log(os.tmpdir());
console.log(process.env.TMPDIR ?? '(TMPDIR not set)');
/tmp
(TMPDIR not set)
On Windows it prints something like C:\Users\<user>\AppData\Local\Temp.
The value comes from environment variables: TMPDIR, TMP or TEMP on Unix (falling back to /tmp), and TEMP or TMP on Windows. That lets users and containers move temp files elsewhere, for example to a bigger disk:
$ TMPDIR=/var/tmp/ node tmpdir.mjs
/var/tmp
/var/tmp/
Notice that os.tmpdir() strips the trailing slash. Always build paths with path.join() instead of concatenating strings.
Never hard-code /tmp. It doesn't exist on Windows, and it ignores the user's TMPDIR.
Creating a unique temp directory with mkdtemp
The safest and most convenient approach is to create a fresh, uniquely named directory and put all your files inside it. fs.mkdtemp(prefix) appends 6 random characters to prefix and creates the directory atomically:
import { mkdtemp, writeFile, readdir, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
const dir = await mkdtemp(join(tmpdir(), 'myapp-'));
console.log('created', dir);
await writeFile(join(dir, 'data.txt'), 'hello');
await writeFile(join(dir, 'other.txt'), 'world');
console.log(await readdir(dir));
await rm(dir, { recursive: true, force: true });
console.log('removed');
created /tmp/myapp-hWc0xD
[ 'data.txt', 'other.txt' ]
removed
Things to know:
- The directory is created with mode
0o700, so on Unix other users can't list or read it. Files inside it can then have simple, fixed names likedata.txt. rm()withrecursive: truedeletes the whole tree;force: truemakes it not fail if the directory is already gone.- There is also a synchronous
mkdtempSync()innode:fs.
A common mistake is to pass os.tmpdir() as the prefix without a separator. The random characters are appended directly, so you try to create a sibling of /tmp, not a child:
mkdtempSync(os.tmpdir()); // tries to create '/tmpXXXXXX'
Error: EACCES: permission denied, mkdtemp '/tmpXXXXXX'
Use join(tmpdir(), 'prefix-'), or tmpdir() + path.sep if you really want no prefix.
Creating a single temp file
When you need just one file directly in the temp directory, generate a name that can't be guessed and open it with the wx flag:
import { open, stat, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
async function createTempFile(prefix = 'tmp-', suffix = '') {
const path = join(tmpdir(), `${prefix}${randomUUID()}${suffix}`);
// 'wx': create, fail with EEXIST if the path already exists
// 0o600: readable and writable only by the current user
const handle = await open(path, 'wx', 0o600);
return { path, handle };
}
const { path, handle } = await createTempFile('report-', '.csv');
try {
await handle.writeFile('id,name\n1,alice\n');
console.log(path);
console.log('mode', ((await stat(path)).mode & 0o777).toString(8));
} finally {
await handle.close();
await rm(path, { force: true });
}
// opening an existing path with 'wx' fails
const { path: p2, handle: h2 } = await createTempFile();
await h2.close();
try {
await open(p2, 'wx');
} catch (err) {
console.log(err.code);
} finally {
await rm(p2, { force: true });
}
/tmp/report-04e42cb3-27b0-48df-a573-cff26f692a74.csv
mode 600
EEXIST
Why each piece matters:
- Random name (
crypto.randomUUID()): names likemyapp.tmpormyapp-${process.pid}can be predicted. Another process (or another copy of your program) can create that path first. wxflag: the file is created exclusively (O_CREAT | O_EXCL). If anything already exists at that path, including a symlink planted by an attacker,open()fails instead of writing through it. Don't check withfs.existsSync()first and then create; that leaves a window between the check and the creation (see Avoiding race conditions when creating or using an existing directory).- Mode
0o600: the shared temp directory is readable by everyone, so a file created with the default mode (usually0o644after umask) could be read by other users.
Use wx+ if you want to write and read back through the same handle.
Always clean up: try / finally
Temp files that are never deleted slowly fill the disk. Make removal part of the control flow, so it also happens when the work throws. A small helper keeps call sites tidy:
import { mkdtemp, rm, writeFile, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
async function withTempDir(fn) {
const dir = await mkdtemp(join(tmpdir(), 'job-'));
try {
return await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
const result = await withTempDir(async (dir) => {
const file = join(dir, 'input.txt');
await writeFile(file, 'some intermediate data');
return (await readFile(file, 'utf8')).toUpperCase();
});
console.log(result);
try {
await withTempDir(async (dir) => {
console.log('working in', dir);
throw new Error('boom');
});
} catch (err) {
console.log('caught:', err.message);
}
SOME INTERMEDIATE DATA
working in /tmp/job-ojV1Dl
caught: boom
Note the return await fn(dir). Without await, the finally block would run before the promise returned by fn settles, deleting the directory while it's still in use.
Self-cleaning directories with await using
Node.js 24.4 added mkdtempDisposable(). It creates the directory just like mkdtemp(), but returns an object with a path property and a Symbol.asyncDispose method that removes the directory and its contents.
Combine it with the await using declaration (explicit resource management) and the directory is deleted automatically when the enclosing block exits, normally or by an exception:
import { mkdtempDisposable, writeFile, access } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
let saved;
{
await using tmp = await mkdtempDisposable(join(tmpdir(), 'build-'));
console.log(tmp.path);
await writeFile(join(tmp.path, 'out.o'), 'object code');
saved = tmp.path;
} // tmp.path and everything in it is removed here
try {
await access(saved);
} catch (err) {
console.log(err.code);
}
/tmp/build-3CAONy
ENOENT
The synchronous version, mkdtempDisposableSync() from node:fs, works with plain using:
import { mkdtempDisposableSync, writeFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
function convert(text) {
using tmp = mkdtempDisposableSync(join(tmpdir(), 'conv-'));
writeFileSync(join(tmp.path, 'in.txt'), text);
if (text.length === 0) {
throw new Error('empty input'); // tmp is still removed
}
return [tmp.path, text.length];
}
const [dir, len] = convert('abc');
console.log(len, existsSync(dir));
try {
convert('');
} catch (err) {
console.log(err.message);
}
3 false
empty input
This is the cleanest option when you can require Node.js 24.4 or later. On older versions use the try / finally helper above.
A disposable temp file class
You can give your own objects the same behavior by implementing Symbol.asyncDispose. Here is a temp file that closes its handle and deletes itself:
import { open, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
class TempFile {
#handle;
constructor(name, path, handle) {
this.name = name;
this.path = path;
this.#handle = handle;
}
static async create(name) {
const path = join(tmpdir(), `${name}-${randomUUID()}`);
return new TempFile(name, path, await open(path, 'wx+', 0o600));
}
async write(text) {
await this.#handle.write(text);
}
async read() {
const buffer = Buffer.alloc(1024);
const { bytesRead } = await this.#handle.read(buffer, 0, buffer.length, 0);
return buffer.toString('utf8', 0, bytesRead);
}
async [Symbol.asyncDispose]() {
await this.#handle.close();
await rm(this.path, { force: true });
console.log('disposed', this.name);
}
}
{
await using a = await TempFile.create('a');
await using b = await TempFile.create('b');
await a.write('first');
await b.write('second');
console.log(await a.read(), await b.read());
}
console.log('done');
first second
disposed b
disposed a
done
Resources are disposed in reverse order of declaration, the same way nested try / finally blocks would unwind.
Cleaning up when the process exits
finally and using don't help with temp files that live as long as the process, such as a cache directory of a server. For those, register a cleanup on the exit event. exit handlers must be synchronous, so use rmSync():
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
const tempDirs = new Set();
function makeTempDir(prefix) {
const dir = mkdtempSync(join(tmpdir(), prefix));
tempDirs.add(dir);
return dir;
}
function cleanup() {
for (const dir of tempDirs) {
rmSync(dir, { recursive: true, force: true });
console.log('cleanup', dir);
}
tempDirs.clear();
}
// 'exit' handlers must be synchronous
process.on('exit', cleanup);
// signals don't trigger 'exit' by default; exit explicitly
for (const sig of ['SIGINT', 'SIGTERM']) {
process.on(sig, () => process.exit(128 + (sig === 'SIGINT' ? 2 : 15)));
}
const dir = makeTempDir('server-');
writeFileSync(join(dir, 'cache.bin'), Buffer.alloc(16));
console.log('running, pid', process.pid);
if (process.argv[2] === 'wait') {
setInterval(() => {}, 1000);
}
Running it to completion, and then running it as a long-lived process killed with SIGTERM:
$ node exit-cleanup.mjs
running, pid 1408
cleanup /tmp/server-13zeQ6
$ node exit-cleanup.mjs wait &
running, pid 1417
$ kill -TERM 1417
cleanup /tmp/server-BMbgUt
Without the signal handlers, Ctrl+C or kill terminates Node.js immediately and the exit event never fires. Nothing runs on SIGKILL or a crash of the machine, so temp data can still be left behind. That's acceptable: the OS cleans the temp directory eventually (on reboot or by age, e.g. systemd-tmpfiles), which is one more reason to keep temp files in os.tmpdir() and not in your project directory.
For a server, combine this with a full Graceful shutdown.
Atomic writes: temp file then rename
Writing directly to an important file (a config, a database snapshot) is risky: if the process dies halfway, the file is left truncated. The standard fix is to write the new content to a temp file and then rename() it over the target. On POSIX systems rename() within a filesystem is atomic: readers see either the old file or the new one, never a partial one.
import { writeFile, rename, rm, readFile } from 'node:fs/promises';
import { dirname, basename, join } from 'node:path';
import { randomBytes } from 'node:crypto';
async function writeFileAtomic(path, data) {
// the temp file must be on the same filesystem as the target,
// so create it in the same directory, not in os.tmpdir()
const tmp = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString('hex')}.tmp`);
try {
await writeFile(tmp, data, { flag: 'wx', flush: true });
await rename(tmp, path);
} catch (err) {
await rm(tmp, { force: true });
throw err;
}
}
await writeFileAtomic('settings.json', JSON.stringify({ theme: 'dark' }));
console.log(await readFile('settings.json', 'utf8'));
await writeFileAtomic('settings.json', JSON.stringify({ theme: 'light' }));
console.log(await readFile('settings.json', 'utf8'));
await rm('settings.json');
{"theme":"dark"}
{"theme":"light"}
Here the temp file is deliberately not in os.tmpdir(). /tmp is often a separate filesystem (tmpfs), and renaming across filesystems fails with EXDEV. The flush: true option calls fsync() before closing, so the data is on disk before the rename makes it visible.
The same pattern works for downloads: stream into file.part, then rename to file once the download completes.
Temp directories in tests
Tests that touch the filesystem should each get their own directory, so they can run in parallel and never see each other's leftovers. With the built-in test runner, create it in beforeEach and remove it in afterEach, or register cleanup with t.after() inside a single test:
import { test, describe, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, rm, writeFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
// code under test
async function countJsonFiles(dir) {
return (await readdir(dir)).filter((f) => f.endsWith('.json')).length;
}
describe('countJsonFiles', () => {
let dir;
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'test-'));
});
afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});
test('empty directory', async () => {
assert.equal(await countJsonFiles(dir), 0);
});
test('mixed files', async () => {
await writeFile(join(dir, 'a.json'), '{}');
await writeFile(join(dir, 'b.json'), '{}');
await writeFile(join(dir, 'c.txt'), '');
assert.equal(await countJsonFiles(dir), 2);
});
});
test('using t.after()', async (t) => {
const dir = await mkdtemp(join(tmpdir(), 'test-'));
t.after(() => rm(dir, { recursive: true, force: true }));
await writeFile(join(dir, 'x.json'), '{}');
assert.equal(await countJsonFiles(dir), 1);
});
$ node --test count.test.mjs
▶ countJsonFiles
✔ empty directory (10.27988ms)
✔ mixed files (8.886064ms)
✔ countJsonFiles (21.779781ms)
✔ using t.after() (5.115986ms)
ℹ tests 3
ℹ suites 1
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 166.895455
Hooks run even when the test fails, so a failing assertion doesn't leak directories.
Passing data to another program
Many command-line tools take file names, not stdin. A temp directory is the natural place for their input and output files:
import { mkdtempDisposable, writeFile } from 'node:fs/promises';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
const run = promisify(execFile);
await using tmp = await mkdtempDisposable(join(tmpdir(), 'sort-'));
const input = join(tmp.path, 'input.txt');
await writeFile(input, 'pear\napple\nbanana\napple\n');
const { stdout } = await run('sort', ['-u', input]);
console.log(stdout.trim().split('\n'));
[ 'apple', 'banana', 'pear' ]
execFile() passes the path as a separate argument, without a shell, so spaces or special characters in the temp path can't break the command. See Child Process for more about running programs.
Summary
- Get the location from
os.tmpdir(); never hard-code/tmp. - Prefer a private directory from
mkdtemp(join(tmpdir(), 'prefix-'))and put files inside it. - For a standalone file use an unguessable name (
crypto.randomUUID()), thewxflag and mode0o600. - Remove temp data in
finally, or letawait usingwithmkdtempDisposable()do it (Node.js 24.4+). - For process-lifetime temp data, clean up synchronously on
exitand handleSIGINT/SIGTERM. - For atomic replacement, write the temp file next to the target and
rename()it. - On npm, the tmp package offers the same features with a callback API and automatic cleanup on exit, but with modern Node.js the core APIs above are usually enough.