74 lines
1.8 KiB
TypeScript
74 lines
1.8 KiB
TypeScript
import fs, { readFileSync } from "fs";
|
|
import { MongoClient } from "mongodb";
|
|
import util from "util";
|
|
|
|
const write = util.promisify(fs.writeFile);
|
|
const read = util.promisify(fs.readFile);
|
|
|
|
class Store {
|
|
filename: string;
|
|
record: Record<string, string>;
|
|
constructor(filename: string) {
|
|
this.filename = filename;
|
|
try {
|
|
this.record = JSON.parse(readFileSync(filename, "utf8"));
|
|
} catch {
|
|
this.record = {};
|
|
}
|
|
}
|
|
public get() {
|
|
return this.record;
|
|
}
|
|
public set(key: string, val: string) {
|
|
this.record[key] = val;
|
|
}
|
|
public delete(key: string) {
|
|
delete this.record[key];
|
|
}
|
|
public async update(record: Record<string, string>) {
|
|
this.record = record;
|
|
await this.save();
|
|
}
|
|
public async save() {
|
|
// try first, then catch
|
|
try {
|
|
console.log("store::index: save record", this.record);
|
|
await write(this.filename, JSON.stringify(this.record), "utf8");
|
|
} catch {
|
|
console.error("store::index: save record error, filename:", this.filename);
|
|
}
|
|
}
|
|
}
|
|
|
|
class HTML {
|
|
html: string;
|
|
filename: string;
|
|
constructor(filename: string) {
|
|
this.filename = filename;
|
|
// load from file
|
|
try {
|
|
this.html = fs.readFileSync(this.filename, "utf8");
|
|
} catch {
|
|
this.html = "";
|
|
}
|
|
}
|
|
public get() {
|
|
return this.html;
|
|
}
|
|
public async set(html: string) {
|
|
this.html = html;
|
|
// store into file
|
|
// try first, then catch
|
|
try {
|
|
await write(this.filename, html, "utf8");
|
|
} catch {
|
|
console.error("store::index: save record error, filename:", this.filename);
|
|
}
|
|
}
|
|
}
|
|
|
|
export const html = new HTML("./data/html-current.html");
|
|
export const htmlRegular = new HTML("./data/html-regular.html");
|
|
export const store = new Store("./data/store.json");
|
|
export const regular = new Store("./data/regular.json");
|