Files
makelore/electron/coding-projects/atomic-json.ts

28 lines
1.0 KiB
TypeScript

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<void>;
export async function atomicWriteText(filePath: string, source: string): Promise<void> {
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<void> {
await atomicWriteText(filePath, `${JSON.stringify(value, null, 2)}\n`);
}
export async function readJsonFile(filePath: string): Promise<unknown> {
return JSON.parse(await readFile(filePath, 'utf8')) as unknown;
}