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.
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.
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'));{"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.