[Utils > Settings] Major source cleanup

This commit is contained in:
Ducko 2022-03-28 08:31:52 +01:00
parent 88f482e017
commit 4e18696b43
1 changed files with 13 additions and 22 deletions

View File

@ -1,25 +1,24 @@
const { readFileSync, statSync, writeFileSync } = require('fs'); const fs = require('fs');
const { join } = require('path'); const { join } = require('path');
class Settings { // Heavily based on original for compat, but simplified and tweaked module.exports = class Settings { // Heavily based on original for compat, but simplified and tweaked
constructor(root) { constructor(root) {
this.path = join(root, 'settings.json'); this.path = join(root, 'settings.json');
try { try {
this.lastSaved = readFileSync(this.path); this.settings = JSON.parse(fs.readFileSync(this.path));
this.settings = JSON.parse(this.lastSaved);
} catch (e) { } catch (e) {
this.settings = {}; this.settings = {};
} }
this.lastModified = this.getLastModified(); this.mod = this.getMod();
log('AppSettings', this.path, this.settings); log('AppSettings', this.path, this.settings);
} }
getLastModified() { getMod() { // Get when file was last modified
try { try {
return statSync(this.path).mtime.getTime(); return fs.statSync(this.path).mtime.getTime();
} catch (e) { } catch (e) {
return 0; return 0;
} }
@ -34,25 +33,17 @@ class Settings { // Heavily based on original for compat, but simplified and twe
} }
save() { save() {
if (this.lastModified && this.lastModified !== this.getLastModified()) return; // File was last modified after Settings was made, so was externally edited therefore we don't save over 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 { try {
const toSave = JSON.stringify(this.settings, null, 2); const str = JSON.stringify(this.settings, null, 2);
if (this.lastSaved != toSave) { // Settings has changed fs.writeFileSync(this.path, str);
this.lastSaved = toSave; this.mod = this.getMod();
writeFileSync(this.path, toSave); log('AppSettings', 'Saved');
this.lastModified = this.getLastModified();
}
log('AppSettings', 'Saved', this.path);
} catch (e) { } catch (e) {
log('AppSettings', 'Failed', this.path, e); log('AppSettings', e);
} }
} }
}
}
module.exports = Settings;