Structured libs

This commit is contained in:
2026-02-14 16:42:11 +01:00
parent a7e29867b8
commit 1331e36177
15 changed files with 42 additions and 38 deletions
+33
View File
@@ -0,0 +1,33 @@
import { promises as fs } from "fs";
import path from "path";
export async function read<T extends object>(
template: () => T,
fp: string,
...filePaths: string[]
): Promise<T> {
const filePath = path.join(process.cwd(), fp, ...filePaths);
const dirPath = path.dirname(filePath);
try {
await fs.access(filePath);
} catch {
await fs.mkdir(dirPath, { recursive: true });
await fs.writeFile(filePath, JSON.stringify(template(), null, 2), "utf-8");
}
const content = await fs.readFile(filePath, "utf-8");
return JSON.parse(content);
}
export async function write<T extends object>(
val: T,
fp: string,
...filePaths: string[]
) {
const filePath = path.join(process.cwd(), fp, ...filePaths);
const dirPath = path.dirname(filePath);
await fs.mkdir(dirPath, { recursive: true });
await fs.writeFile(filePath, JSON.stringify(val, null, 2), "utf-8");
}