import { randomUUID } from 'node:crypto'; import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; export type JsonFileWriter = (filePath: string, value: unknown) => Promise; export async function atomicWriteText(filePath: string, source: string): Promise { await mkdir(path.dirname(filePath), { recursive: true }); const temporaryPath = path.join( path.dirname(filePath), `.${path.basename(filePath)}.${randomUUID()}.tmp`, ); try { await writeFile(temporaryPath, source, { encoding: 'utf8', flag: 'wx' }); await rename(temporaryPath, filePath); } finally { await rm(temporaryPath, { force: true }).catch(() => undefined); } } export async function atomicWriteJson(filePath: string, value: unknown): Promise { await atomicWriteText(filePath, `${JSON.stringify(value, null, 2)}\n`); } export async function readJsonFile(filePath: string): Promise { return JSON.parse(await readFile(filePath, 'utf8')) as unknown; }