Skip to content
jshacks.dev
Node.js

Write a file atomically with a temp file and rename

Write a file atomically with a temp file and rename in Node.js, so readers never see a half-written file after a crash. Node.js 24.

1 min read
Summarize in AI

Writing straight to a file leaves it half written if the process dies. Write a temporary file in the same folder and rename it over the target, which replaces it in one step.

JavaScript
import { writeFile, rename, readFile } from 'node:fs/promises';

async function writeAtomic(path, data) {
  const temp = `${path}.${process.pid}.tmp`;
  await writeFile(temp, data);
  await rename(temp, path);
}

await writeFile('config.json', '{"v":1}');
await writeAtomic('config.json', '{"v":2}');
console.log(await readFile('config.json', 'utf8'));
Text
{"v":2}

A rename within one file system is atomic on POSIX systems: a reader opens either the old file or the new one, never a mix. The temporary file must sit on the same volume, which is why it is a sibling of the target and not in os.tmpdir().

For power-loss safety, call fsync on the temp file before the rename. On Windows, rename over an open file can fail with EPERM, so retry or use a library such as write-file-atomic.

Taggednode 24
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.