git-subtree-dir: estore git-subtree-mainline: 746868d720b9be1003a2f783b7a12d526d8eea60 git-subtree-split: e34dfc397c94025670baa2b73b482c01f3033a6a
15 lines
546 B
TypeScript
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)
|
|
}
|