A config file that worked five seconds ago is now a 347-byte fragment of broken JSON. Your CLI tool will not start. The user, who simply pressed Ctrl-C because the update was taking longer than expected, is now staring at an error stack trace they did not ask for. The two kilobytes of valid configuration that existed before the write are gone, replaced by the digital equivalent of a half-printed receipt.

This happens because writeFile is not atomic. It opens the existing path, truncates it, streams data from Node into the kernel’s page cache, and eventually closes the file descriptor. The moment the truncation happens, the old content is already gone. Everything between that truncation and the final close is a window of vulnerability. A SIGINT, a power outage, or a laptop lid slamming shut during that window leaves the filesystem holding a truncated mess. Even if Node reports the Promise as resolved, the operating system may still be buffering writes in memory. Convenience methods hide that gap, but they do not remove it.

The fix is not to write in place. The fix is to separate the act of writing from the act of publishing.

Write to a sibling, then swap

The reliable pattern has five steps. None of them are complicated, but together they move the failure window from an entire streaming write down to a single filesystem metadata operation.

First, serialize the entire payload in memory. Do this before you create any temporary file. If JSON.stringify throws because someone passed a circular object, you want that exception to bubble up before you touch the disk.

Second, write the serialized data to a temporary file located in the same directory as the target. Use a randomized name so two concurrent runs do not collide. Keeping the temp file in the same directory matters because rename is only atomic within a single filesystem. If your temp file lives on a different partition, the operating system falls back to a copy-and-delete sequence, which introduces its own failure modes and is no longer atomic.

Third, ask the kernel to flush that temporary file to physical storage. Node’s fsync, exposed here as the sync method on a filehandle, blocks until the buffers are down on the metal. This is slow, but config writes happen rarely enough that the durability is worth the milliseconds.

Fourth, rename the temporary file over the original path. On both POSIX systems and Windows, this is the commit point. Readers opening the original path will see either the complete old file or the complete new file. There is no moment in time where a reader can open the path and observe a half-written buffer.

Fifth, sync the parent directory. This catches a subtle edge case. The rename updates the directory entry, but the directory metadata itself might sit in the kernel’s page cache. Sudden power loss after a successful rename can sometimes leave the filesystem in a state where the new inode reference was never recorded durably. Syncing the directory forces that metadata update to disk and seals the transaction.

A concrete Node.js implementation

Here is what that pattern looks like in practice using only the Node.js standard library:

import { open, rename, rm } from "node:fs/promises";
import { dirname, basename, join } from "node:path";
import { randomUUID } from "node:crypto";

export async function writeJsonAtomic(path, value) {
  const directory = dirname(path);
  const temporary = join(directory, `.${basename(path)}.${randomUUID()}.tmp`);
  const body = `${JSON.stringify(value, null, 2)}\n`;
  let handle;

  try {
    handle = await open(temporary, "wx", 0o600);
    await handle.writeFile(body, "utf8");
    await handle.sync();
    await handle.close();
    handle = undefined;

    await rename(temporary, path);

    const directoryHandle = await open(directory, "r");
    try {
      await directoryHandle.sync();
    } finally {
      await directoryHandle.close();
    }
  } catch (error) {
    if (handle) await handle.close().catch(() => {});
    await rm(temporary, { force: true }).catch(() => {});
    throw error;
  }
}

A few details in this code are worth attention.

The wx flag means “write, but fail if the file already exists.” This guards against a UUID collision or an abandoned temp file from a previous crashed process. If someone has dropped a malicious file where your temp file should be, you will hear about it immediately rather than overwriting whatever is there.

The 0o600 permission mask creates the temp file with owner-read and owner-write only. Config files frequently hold secrets, API tokens, or private repository URLs. There is no reason to let other users on the system peek at the temporary file while it is being prepared.

Notice the separate sync calls on the file and then on the directory. Many developers skip the directory sync because it feels redundant. It is not. Ext4, APFS, and NTFS all handle directory updates differently, but they share a common habit of batching metadata writes for performance. If you care about surviving power loss, the directory sync is the final seal.

การทำ cleanup ใน catch block นั้นถูกออกแบบมาเพื่อป้องกันความผิดพลาดโดยเฉพาะ หากมีอะไรก็ตามที่ throw หลังจากเปิด filehandle แล้ว โค้ดจะพยายามปิด handle และลบไฟล์ชั่วคราวทิ้ง โดยจะทำการกลืน (swallow) error รองใดๆ เพื่อให้ exception ดั้งเดิมสามารถส่งต่อ (propagate) ออกไปได้อย่างชัดเจน คุณคงไม่ต้องการให้ error เรื่องสิทธิ์การเข้าถึง (permission error) ระหว่างการ cleanup มาบดบัง bug ที่แท้จริงซึ่งเป็นสาเหตุของความล้มเหลว

เมื่อรูปแบบนี้เริ่มช่วยอะไรไม่ได้แล้ว

การแทนที่ไฟล์แบบ atomic ช่วยป้องกัน torn writes แต่ไม่สามารถป้องกัน lost updates ได้ หาก CLI สอง instance อ่าน config เดียวกันพร้อมกัน ทั้งคู่ทำการแก้ไขในหน่วยความจำ (memory) ทั้งคู่เขียนไฟล์ชั่วคราวใหม่ และทั้งคู่สั่ง rename ไฟล์ ผลคือการ rename ครั้งที่สองจะเป็นฝ่ายชนะ กระบวนการแรกไม่ได้สังเกตเห็นการเปลี่ยนแปลงของกระบวนการที่สอง ซึ่งขึ้นอยู่กับแอปพลิเคชันของคุณ สิ่งนี้อาจหมายความว่าผู้ใช้คนหนึ่งเพิ่มการตั้งค่าใน terminal หนึ่ง และผู้ใช้อีกคนลบการตั้งค่าออกในอีก terminal หนึ่ง โดยไฟล์สุดท้ายจะสะท้อนเฉพาะสิ่งที่ผู้เขียนคนล่าสุดทำเท่านั้น

หากเครื่องมือของคุณจำเป็นต้องรองรับการแก้ไขข้อมูลพร้อมกัน (concurrent mutators) คุณต้องมีกลไกการประสานงาน (coordination mechanism) เสริมจากการเขียนแบบ atomic การใช้ advisory lock file สามารถใช้ได้กับกรณีง่ายๆ ส่วน version vectors หรือเลข revision แบบ monotonic ภายในตัว config เองสามารถช่วยตรวจจับการชนกันของข้อมูล (collisions) เพื่อให้ผู้เขียนคนที่สองสามารถลองใหม่ได้ สิ่งเหล่านี้จะเพิ่มความซับซ้อน และความซับซ้อนนี่แหละคือที่ที่ bug มักจะซ่อนตัวอยู่

นั่นคือเหตุผลที่ขอบเขต (boundary) มีความสำคัญ JSON blob เพียงชุดเดียวที่หนึ่งกระบวนการอัปเดตเป็นครั้งคราวถือเป็นตัวเลือกที่ดีสำหรับการเขียนไฟล์แบบ atomic แต่เมื่อใดก็ตามที่คุณเริ่มต้องจัดการกับข้อมูลหลายเรคคอร์ด (multiple records) การบังคับใช้ schema หรือต้องกังวลเรื่องการแก้ไขข้อมูลพร้อมกัน (concurrent mutations) นั่นแสดงว่าคุณใช้งานเกินขีดความสามารถของ filesystem ไปแล้ว SQLite ถูกสร้างขึ้นมาด้วยเหตุผลนี้โดยเฉพาะ มันให้ทั้ง atomic transactions, rollback journals และการจัดการผู้อ่านและผู้เขียนที่ทำงานพร้อมกันได้อย่างเหมาะสม ทั้งหมดนี้อยู่ภายในไฟล์เดียวที่เก็บไว้ในเครื่อง (host-local file) โปรโตคอลไฟล์ที่ชาญฉลาดก็ไม่ใช่ฐานข้อมูล และคุณไม่ควรเสียทรัพยากรในการดูแลรักษาไปกับการพยายามทำตัวเป็นฐานข้อมูล

บทเรียนสำคัญที่แท้จริง

ครั้งต่อไปที่คุณคิดจะใช้ writeFile ในเครื่องมือ CLI ให้หยุดคิดสักนิด การทำ serialization ไม่ใช่ส่วนที่ยาก แต่ความทนทานของข้อมูล (durability) ต่างหากที่ยาก ไฟล์ config นั้นเล็กเกินกว่าจะใช้วิธี streaming และสำคัญเกินกว่าจะใช้วิธี truncate ให้เขียน payload ทั้งหมดลงในไฟล์คู่ขนานที่ซ่อนอยู่ (hidden sibling) จากนั้นทำการ flush, commit ด้วยการ rename และแจ้งการเปลี่ยนแปลงให้ directory รับทราบ ผู้ใช้ของคุณอาจจะกด Ctrl-C, กระชากปลั๊กไฟออก หรือปิดฝาโน้ตบุ๊ก เมื่อเครื่องกลับมาทำงานอีกครั้ง ไฟล์จะมีข้อมูลของโลกใบเก่าหรือโลกใบใหม่เท่านั้น จะไม่มีสถานะที่อยู่ตรงกลางระหว่างสองอย่างนั้น