55 lines
No EOL
1.3 KiB
TypeScript
55 lines
No EOL
1.3 KiB
TypeScript
/**
|
|
* Store — centralized file I/O for JSON data.
|
|
* Replaces scattered fs.readFileSync/writeFileSync calls.
|
|
*
|
|
* Usage:
|
|
* import { Store } from "@systems/store";
|
|
*
|
|
* const data = Store.read<MyType>("path/to/file.json");
|
|
* Store.write("path/to/file.json", data);
|
|
* const data = Store.readOrDefault<MyType>("path/to/file.json", {});
|
|
*/
|
|
|
|
import fs from "fs";
|
|
|
|
export const Store = {
|
|
/**
|
|
* Read and parse a JSON file.
|
|
* Returns null if file doesn't exist or can't be parsed.
|
|
*/
|
|
read<T>(filePath: string): T | null {
|
|
try {
|
|
return JSON.parse(fs.readFileSync(filePath, "utf8")) as T;
|
|
} catch {
|
|
return null;
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Read and parse a JSON file, returning a default value on failure.
|
|
*/
|
|
readOrDefault<T>(filePath: string, defaultValue: T): T {
|
|
return Store.read<T>(filePath) ?? defaultValue;
|
|
},
|
|
|
|
/**
|
|
* Serialize and write data to a JSON file.
|
|
*/
|
|
write<T>(filePath: string, data: T): void {
|
|
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
|
|
},
|
|
|
|
/**
|
|
* Check if a file exists.
|
|
*/
|
|
exists(filePath: string): boolean {
|
|
return fs.existsSync(filePath);
|
|
},
|
|
|
|
/**
|
|
* Delete a file if it exists.
|
|
*/
|
|
delete(filePath: string): void {
|
|
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
|
},
|
|
}; |