2021-05-04 17:04:14 +02:00
|
|
|
import {promises as fs, readFileSync} from "fs";
|
2021-03-24 21:41:13 +01:00
|
|
|
|
|
|
|
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> {
|
2021-05-04 17:04:14 +02:00
|
|
|
this.cache[file] = (await fs.readFile(file)).toString();
|
2021-03-24 21:41:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
public loadSync(file: string): void {
|
2021-05-04 17:04:14 +02:00
|
|
|
this.cache[file] = readFileSync(file).toString();
|
2021-03-24 21:41:13 +01:00
|
|
|
}
|
|
|
|
}
|