import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; /** * Writes data to a JSON file atomically using a temp-file-and-rename strategy. * This prevents file corruption if the process crashes or is killed during writing. * * @param filePath Path to the target file. * @param data Data to be JSON-serialized and written. */ export function writeJsonAtomic(filePath: string, data: any): void { const tmpPath = filePath + ".tmp"; try { writeFileSync(tmpPath, JSON.stringify(data, null, 2), "utf-8"); renameSync(tmpPath, filePath); } catch (err) { // Attempt cleanup if rename failed try { if (existsSync(tmpPath)) unlinkSync(tmpPath); } catch { // ignore cleanup errors } throw err; } } /** * Reads data from a JSON file. Returns undefined if the file doesn't exist or is corrupt. */ export function readJsonSafe(filePath: string): T | undefined { if (!existsSync(filePath)) return undefined; try { return JSON.parse(readFileSync(filePath, "utf-8")) as T; } catch { return undefined; } }