Node.js Reference ยท fs and fs/promises
Node.js fs.mkdtemp() method
Reference for fs.mkdtemp() in Node.js: create a uniquely named temporary directory from a prefix, use os.tmpdir(), clean up safely and the disposable variant.
fs.mkdtemp(prefix, callback) creates a new directory whose name is your prefix followed by six random characters, and gives you its path. Because the operating system picks the characters and creates the directory in one step, two programs can never receive the same directory, and nobody can plant a look-alike directory first.
This is the safe way to get scratch space for tests, downloads, build output or anything that should not collide with other runs. Node does not delete the directory for you; removing it is your job.
import fs from "node:fs"; import os from "node:os"; import path from "node:path"; const dir = fs.mkdtempSync(path.join(os.tmpdir(), "report-"));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
fs.mkdtemp(prefix[, options], callback) // callback(err, directory) fs.mkdtempSync(prefix[, options]): string fsPromises.mkdtemp(prefix[, options]): Promise<string>
| Name | Description |
|---|---|
prefix |
A string or Buffer path prefix. Six random characters are appended directly to it. |
options |
An encoding string, or { encoding }. Default "utf8"; "buffer" returns a Buffer. |
callback |
Called as callback(err, directory). |
Returns: the path of the new directory, as written (relative if the prefix was relative).
Errors: ENOENT if the parent folder of the prefix does not exist, EACCES without permission, ERR_INVALID_ARG_TYPE for a non-string prefix.
Usage notes
- No separator is inserted.
"/tmp/job"gives/tmp/jobA1b2C3. End the prefix with-or/(a trailing slash makes the temp directory live inside a folder) depending on what you want. - Use
os.tmpdir()as the base so the code works on every platform and respectsTMPDIR. - Permissions are private. The directory is created with mode
0o700, so other users cannot read it. - Clean up in
finally. Temp directories survive crashes and fill disks. Remove them withfs.rm(dir, { recursive: true, force: true }). - Disposable form: recent Node 24 releases add
fs.mkdtempDisposableSync()andfsPromises.mkdtempDisposable(), which return an object withpathand aremove()method that also works withusing. Check that your Node version has it before relying on it. - Do not build the name yourself from random numbers or timestamps. That is how predictable-name attacks happen.