Temporary files are commonly used in Node.js applications for storing intermediate data, processing uploads, generating reports, handling downloads, and performing file conversions. These files are useful because applications can work with temporary data without permanently storing every intermediate result.
However, creating temporary files securely is important. If an application generates predictable file names or checks whether a file exists before creating it, another process may interfere with the operation. This can introduce security problems, including file replacement and unauthorized access.
Node.js 26.14 introduces the fs.mkstemp() API and its Promise-based equivalent, fsPromises.mkstemp(). These methods create and open a uniquely named temporary file in a single operation. This helps prevent another process from creating a file with the same name between the name-generation and file-creation steps.
This article explains how to use fs.mkstemp() in Node.js, how it differs from existing file-system methods, and how to manage temporary files safely in production applications.
Why Secure Temporary File Creation Matters
Applications frequently need temporary storage while performing operations. For example, an application might download a document, extract its contents, transform the data, and then upload the processed result to another service.
A common approach is to generate a temporary file name and then create the file using a separate operation. However, this approach can introduce a race condition.
Consider the following example:
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const crypto = require('node:crypto');
const fileName = path.join(
os.tmpdir(),
`report-${crypto.randomUUID()}.txt`
);
if (!fs.existsSync(fileName)) {
fs.writeFileSync(fileName, 'Temporary report data');
}
The application first checks whether the file exists and then writes to it. Between these two operations, another process could create a file with the same name.
This is a time-of-check to time-of-use problem. The application checks a condition, but the file system can change before the application uses that result.
Using a unique name reduces the likelihood of a collision, but checking and creating the file separately still leaves a race condition.
A safer approach is to create and open the temporary file in a single operation.
What Is fs.mkstemp() in Node.js 26.14?
The fs.mkstemp() method creates and opens a uniquely named temporary file. It was introduced in Node.js 26.14 and is currently marked as experimental.
The method accepts a prefix and a callback. Node.js appends six random characters to the supplied prefix and creates the file.
The callback receives an error and a file object containing the file path and an open file descriptor.
The Promise-based version, fsPromises.mkstemp(), returns an object containing the generated path and a FileHandle.
The important difference is that file creation and opening happen together. Another process cannot create a file with the same name between those two operations.
On POSIX systems, the created file is readable and writable only by its owner.
Here are the two available approaches:
const fs = require('node:fs');
// Callback-based API
fs.mkstemp('/tmp/report-', (error, file) => {
if (error) {
console.error(error);
return;
}
console.log(file.path);
console.log(file.fd);
});
const { mkstemp } = require('node:fs/promises');
async function createTemporaryFile() {
const file = await mkstemp('/tmp/report-');
console.log(file.path);
await file.handle.close();
}
createTemporaryFile().catch(console.error);
Both examples create a temporary file with a generated name. The Promise-based version is particularly convenient when an application already uses async and await for file operations.
Creating a Temporary File With fsPromises.mkstemp()
The Promise-based API is a good choice for modern Node.js applications because it makes asynchronous file operations easier to organize.
The following example creates a temporary file, writes some content, and closes the file handle:
const { mkstemp } = require('node:fs/promises');
const { join } = require('node:path');
const { tmpdir } = require('node:os');
async function createTemporaryFile() {
let file;
try {
const prefix = join(tmpdir(), 'report-');
file = await mkstemp(prefix);
await file.handle.writeFile(
'This is temporary report data.'
);
console.log('Temporary file:', file.path);
} catch (error) {
console.error('Temporary file creation failed:', error);
} finally {
if (file) {
await file.handle.close();
}
}
}
createTemporaryFile();
The example uses the operating system's temporary directory rather than hardcoding a directory path. This makes the code more portable across different environments.
The generated file name contains the supplied prefix followed by random characters. The application can use the returned path whenever another operation needs to access the file.
The FileHandle remains open until the application closes it. Closing the handle releases the associated file resource, but it does not remove the file from the file system.
Writing and Reading Temporary File Data
A temporary file is useful only when an application can safely write and read its contents.
The following example creates a temporary file, writes data, reads it back, and removes the file after processing:
const { mkstemp, readFile, unlink } = require('node:fs/promises');
const { join } = require('node:path');
const { tmpdir } = require('node:os');
async function processTemporaryData() {
let file;
try {
file = await mkstemp(join(tmpdir(), 'processing-'));
await file.handle.writeFile(
JSON.stringify({
status: 'completed',
records: 150
})
);
await file.handle.close();
file = null;
const content = await readFile(
filePath,
'utf8'
);
console.log('Processed data:', content);
} catch (error) {
console.error('Processing failed:', error);
} finally {
if (file) {
await file.handle.close().catch(() => {});
}
}
}
processTemporaryData();
When implementing this workflow, the application must retain the generated path before closing the handle. The following is the corrected version:
const { mkstemp, readFile, unlink } = require('node:fs/promises');
const { join } = require('node:path');
const { tmpdir } = require('node:os');
async function processTemporaryData() {
let file;
let filePath;
try {
file = await mkstemp(join(tmpdir(), 'processing-'));
filePath = file.path;
await file.handle.writeFile(
JSON.stringify({
status: 'completed',
records: 150
})
);
await file.handle.close();
file = null;
const content = await readFile(filePath, 'utf8');
console.log('Processed data:', content);
} catch (error) {
console.error('Processing failed:', error);
} finally {
if (file) {
await file.handle.close().catch(() => {});
}
if (filePath) {
await unlink(filePath).catch(() => {});
}
}
}
processTemporaryData();
This version stores the generated path separately, closes the file handle before reading the file again, and removes the temporary file during cleanup.
In a larger application, cleanup errors should be handled according to the application's logging and error-reporting requirements. Silently ignoring cleanup failures may be acceptable in a small example, but production systems should record failures when temporary files contain sensitive information.
Understanding the Prefix Parameter
The prefix determines where the temporary file is created and how its generated name begins.
For example:
const { mkstemp } = require('node:fs/promises');
const { join } = require('node:path');
const { tmpdir } = require('node:os');
async function createFile() {
const prefix = join(tmpdir(), 'upload-');
const file = await mkstemp(prefix);
console.log(file.path);
await file.handle.close();
}
createFile().catch(console.error);
A generated file name might look like this:
/tmp/upload-aB12xY
The random characters are appended directly to the supplied prefix.
When creating a file inside a particular directory, the prefix must contain the appropriate directory separator or the beginning of the intended file name. Using path.join() helps construct paths correctly across operating systems.
Avoid trailing X characters in the prefix because some platforms treat them differently. Node.js documentation also notes that some platforms can generate more than six random characters.
Difference Between mkstemp() and mkdtemp()
Node.js already provides mkdtemp() for creating unique temporary directories. The new mkstemp() method serves a different purpose.
mkdtemp() creates a directory, while mkstemp() creates and opens a file.
Use mkdtemp() when an operation needs a temporary workspace containing multiple files or directories. Use mkstemp() when the application needs one temporary file.
Another important difference is resource handling. The Promise-based mkstemp() method returns a FileHandle that must be closed by the application. The temporary file must also be removed when it is no longer required.
Neither method should be treated as a complete automatic cleanup solution for temporary resources.
Best Practices for Secure Temporary Files
Use the operating system temporary directory
Avoid hardcoding temporary directory paths. Use os.tmpdir() to obtain the appropriate location for the current operating system.
This improves portability and reduces assumptions about the server environment.
Keep temporary file permissions restrictive
On POSIX systems, mkstemp() creates files that are readable and writable only by their owner. This helps prevent other users from accessing the file through ordinary file permissions.
However, applications should still consider the security of the temporary directory, the operating system account running the application, and any processes that can access the same resources.
Close file handles after processing
An open FileHandle consumes system resources. Always close it after completing the required operations.
Use try and finally blocks so that cleanup is attempted even when writing, reading, or processing fails.
Remove files when they are no longer needed
Creating a temporary file does not mean Node.js will automatically delete it. The application is responsible for removing the file.
Use unlink() when the file is no longer required. Applications should also consider how temporary files will be cleaned up after unexpected termination or server restarts.
Avoid predictable temporary file names
Do not rely on manually generated file names or separate existence checks before creating a file.
Use the path returned by mkstemp() rather than attempting to reconstruct the generated name.
Validate the data written to temporary files
Temporary files can still contain sensitive information. Avoid writing unnecessary credentials, tokens, personal information, or confidential application data.
If sensitive information must be stored temporarily, consider the application's access controls, encryption requirements, retention period, and cleanup strategy.
Common Mistakes to Avoid
Some common mistakes when working with temporary files include:
- Assuming that closing a FileHandle automatically deletes the file.
- Forgetting to close the FileHandle after processing.
- Using a hardcoded temporary directory that may not exist on another operating system.
- Generating a file name and checking its existence before creating the file.
- Assuming that a temporary file is automatically removed when the Node.js process exits.
- Ignoring cleanup errors in applications that handle sensitive data.
- Using mkstemp() when the application actually needs a temporary directory.
Understanding these differences helps prevent resource leaks and reduces the risk of exposing temporary data.
Conclusion
Node.js 26.14 introduces fs.mkstemp() and fsPromises.mkstemp() for creating and opening uniquely named temporary files in a single operation. This approach helps avoid race conditions associated with generating a file name and creating the file separately.
The Promise-based API is especially useful for modern applications because it works naturally with async and await. Developers receive both the generated file path and an open FileHandle, making it straightforward to write and manage temporary data.
However, the API is currently experimental, so developers should consider its stability status before adopting it in production. Applications must also close file handles and remove temporary files when they are no longer needed.
When used with appropriate permissions, error handling, and cleanup practices, mkstemp() provides a safer foundation for temporary file management in Node.js applications.
Join the conversation! Your thoughts help the community grow.