-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfs.ts
More file actions
24 lines (22 loc) · 781 Bytes
/
fs.ts
File metadata and controls
24 lines (22 loc) · 781 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { isRecord } from "./object-type-guards.ts";
export async function readJsonFile<T>(path: string): Promise<T | null> {
try {
const raw = await readFile(path, "utf8");
return JSON.parse(raw) as T;
} catch (err: unknown) {
if (isRecord(err) && err.code === "ENOENT") {
return null;
}
// Corrupted JSON should not brick the CLI; treat as missing.
if (err instanceof SyntaxError) {
return null;
}
throw err;
}
}
export async function writeJsonFile(path: string, data: unknown): Promise<void> {
await mkdir(dirname(path), { recursive: true });
await writeFile(path, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
}