asarfuckery/appasar/stable/common/Settings.js

71 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2019-01-17 18:22:05 +00:00
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// TODO: sync fs operations could cause slowdown and/or freezes, depending on usage
// if this is fine, remove this todo
2019-03-12 17:01:00 +00:00
class Settings {
constructor(root) {
2019-01-17 18:22:05 +00:00
this.path = _path2.default.join(root, 'settings.json');
try {
this.lastSaved = _fs2.default.readFileSync(this.path);
this.settings = JSON.parse(this.lastSaved);
} catch (e) {
this.lastSaved = '';
this.settings = {};
}
this.lastModified = this._lastModified();
}
2019-03-12 17:01:00 +00:00
_lastModified() {
try {
return _fs2.default.statSync(this.path).mtime.getTime();
} catch (e) {
return 0;
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
}
2019-01-17 18:22:05 +00:00
2019-03-12 17:01:00 +00:00
get(key, defaultValue = false) {
if (this.settings.hasOwnProperty(key)) {
return this.settings[key];
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
return defaultValue;
}
set(key, value) {
this.settings[key] = value;
}
save() {
if (this.lastModified && this.lastModified !== this._lastModified()) {
console.warn('Not saving settings, it has been externally modified.');
return;
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
try {
const toSave = JSON.stringify(this.settings, null, 2);
if (this.lastSaved != toSave) {
this.lastSaved = toSave;
_fs2.default.writeFileSync(this.path, toSave);
this.lastModified = this._lastModified();
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
} catch (err) {
console.warn('Failed saving settings with error: ', err);
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
}
}
2019-01-17 18:22:05 +00:00
exports.default = Settings;
module.exports = exports['default'];