How do you write a JSON file in Node.js without risking a half-written file?
Write the data to a temporary file in the same folder, then rename it over the target. Rename is atomic on the same filesystem, so readers see either the old file or the complete new one.
Explain it simply
If you overwrite a file directly and the power goes off halfway, you are left with a broken file, like a result sheet that was erased and only half rewritten. The safer habit is to prepare the new copy on a separate sheet, and only when it is complete, swap it in. Swapping is a single step, so nobody ever sees a half-finished version.
Example
const fsp = require("fs/promises");
const path = require("path");
async function saveJson(file, data) {
const tmp = path.join(
path.dirname(file),
`.${path.basename(file)}.${process.pid}.tmp`
);
await fsp.writeFile(tmp, JSON.stringify(data, null, 2), "utf8");
await fsp.rename(tmp, file); // atomic swap on the same filesystem
}
saveJson("./scores.json", { rohit: 183, virat: 152 });Points to remember:
- The temp file must be on the same filesystem as the target, otherwise rename may copy instead of swap.
- Two processes writing at the same time still need locking or a database.
- For anything beyond a small config or a prototype, a real database is the better store.
What to say in the interview
"I write to a temp file in the same directory and rename it over the original, because rename is atomic. That avoids corrupted JSON if the process dies mid-write."
Common mistakes
- Writing directly with
writeFilewhile other code reads the same file. - Putting the temp file in
/tmp, which may be on a different disk.