Node.js › File System & File Processing

How would you implement atomic file writes in Node.js to avoid leaving a file in a corrupted, half-written state if the process crashes mid-write?

Advanced

Answer

A direct write to a file's final path risks leaving it partially written (corrupted) if the process crashes or is killed mid-operation -- the standard atomic-write pattern instead writes the complete new content to a temporary file first, then uses fs.rename() (which is an atomic operation at the filesystem level on most systems) to move the temp file into the final destination path, ensuring readers only ever see either the complete old version or the complete new version, never a partial write.
const fs = require('node:fs/promises');

async function atomicWriteFile(finalPath, content) {
  const tempPath = `${finalPath}.tmp-${process.pid}`;
  await fs.writeFile(tempPath, content);
  await fs.rename(tempPath, finalPath); // atomic on most filesystems
}
Real-world example A configuration-persistence service switches from writing directly to config.json to writing to a temp file and renaming it into place, eliminating a rare but real bug where a process crash mid-write had occasionally left the production config file truncated and unparseable.

Common follow-ups: Why specifically is fs.rename() atomic while a direct fs.writeFile() to the final path isn't?;Does this atomic-rename guarantee hold across all filesystems and operating systems, or are there exceptions?