var fs = require("fs"); const Rx = require("rx").Rx; export class Database { data: any; name: string; filename: string; changes$: any; constructor(name: string, defaultValue?: any) { try { this.changes$ = new Rx.Subject(); this.name = name; this.filename = `data/${this.name}.json`; var data = JSON.stringify(defaultValue, null, 2); if (defaultValue) { try { fs.writeFileSync(this.filename, data, { flag: "wx" }, function(err) { if (err) { } }); } catch (e) {} } fs.watch( `data/${this.name}.json`, { encoding: "buffer" }, (eventType, fn) => { if (fn) { var f = fs.readFileSync(this.filename); this.data = JSON.parse(f); this.changes$.onNext(); } } ); this.data = JSON.parse(fs.readFileSync(this.filename)); } catch (e) { console.log(e); this.data = {}; } } set(k: string, v: any) { this.data[k] = v; var json = JSON.stringify(this.data, null, 2); fs.writeFileSync(this.filename, json, function(err) { if (err) console.log(err); }); } get(k?: string): any { //todo fix this if (k) return this.data[k]; return this.data; } }