balloon-shop/estore/src/lib/file-utils.ts
chris 21ebb9667b Add 'estore/' from commit 'e34dfc397c94025670baa2b73b482c01f3033a6a'
git-subtree-dir: estore
git-subtree-mainline: 746868d720b9be1003a2f783b7a12d526d8eea60
git-subtree-split: e34dfc397c94025670baa2b73b482c01f3033a6a
2026-04-13 19:22:23 -04:00

15 lines
546 B
TypeScript

import { writeFileSync, renameSync, mkdirSync, existsSync } from 'fs'
import path from 'path'
/**
* Atomically write JSON to a file by writing to a temp file first, then
* renaming it into place. Prevents partial writes from corrupting the file.
*/
export function atomicWriteJSON(filePath: string, data: unknown): void {
const dir = path.dirname(filePath)
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
const tmp = `${filePath}.tmp`
writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf-8')
renameSync(tmp, filePath)
}