OpenAsar/src/appSettings.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

const fs = require('fs');
2021-12-09 16:25:14 +00:00
class Settings { // Heavily based on original for compat, but simplified and tweaked
constructor(path) {
try {
2022-04-22 17:01:15 +00:00
this.store = JSON.parse(fs.readFileSync(path));
} catch {
this.store = {};
}
this.path = path;
this.mod = this.getMod();
2022-04-22 17:01:15 +00:00
log('Settings', this.path, this.store);
}
getMod() { // Get when file was last modified
try {
return fs.statSync(this.path).mtime.getTime();
} catch { }
}
2022-04-22 17:01:15 +00:00
get(k, d) {
return this.store[k] ?? d;
}
2022-04-22 17:01:15 +00:00
set(k, v) {
this.store[k] = v;
}
save() {
if (this.mod && this.mod !== this.getMod()) return; // File was last modified after Settings was made, so was externally edited therefore we don't save over
try {
fs.writeFileSync(this.path, JSON.stringify(this.store, null, 2));
this.mod = this.getMod();
2022-04-22 17:01:15 +00:00
log('Settings', 'Saved');
} catch (e) {
2022-04-22 17:01:15 +00:00
log('Settings', e);
}
}
}
let inst; // Instance of class
exports.getSettings = () => inst = inst ?? new Settings(require('path').join(require('./paths').getUserData(), 'settings.json'));