swaf/src/utils/FileCache.ts

35 lines
945 B
TypeScript

import {promises as fs, readFileSync} from "fs";
export default class FileCache {
private readonly cache: Record<string, string> = {};
public async get(file: string, forceRead: boolean = false): Promise<string> {
if (forceRead || !this.cache[file]) {
await this.load(file);
}
return this.cache[file];
}
public getSync(file: string, forceRead: boolean = false): string {
if (forceRead || !this.cache[file]) {
this.loadSync(file);
}
return this.cache[file];
}
public getOrFail(file: string): string {
if (!this.cache[file]) throw new Error(file + ' not cached.');
return this.cache[file];
}
public async load(file: string): Promise<void> {
this.cache[file] = (await fs.readFile(file)).toString();
}
public loadSync(file: string): void {
this.cache[file] = readFileSync(file).toString();
}
}