Skip to content

Commit

Permalink
save settings
Browse files Browse the repository at this point in the history
  • Loading branch information
greggman committed Mar 4, 2017
1 parent 6ea5531 commit f5a7a64
Showing 1 changed file with 52 additions and 1 deletion.
53 changes: 52 additions & 1 deletion main.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,56 @@ let expressApp = null;
let server = null;
let running = false;
let restart = false;
const settings = {

const dataDir = app.getPath("userData");
const settingsPath = path.join(dataDir, "config.json");
const defaultSettings = {
port: 8080,
root: app.getPath("home"),
local: false,
cors: true,
dirs: true,
index: true,
};
let settings;
try {
settings = JSON.parse(fs.readFileSync(settingsPath, {encoding: 'utf8'}));
const keys = Object.keys(defaultSettings).sort();
if (!compareArrays(keys, Object.keys(settings).sort())) {
throw new Error("bad settings");
}
keys.forEach(key => {
const atype = typeof defaultSettings[key];
const btype = typeof settings[key];
if (atype !== btype) {
throw new Error(`${key} of wrong type. Expected ${atype}, was ${btype}`);
}
});
} catch (e) {
settings = Object.assign({}, defaultSettings);
}

function compareArrays(a, b) {
if (!a) {
return (!b);
} else if (!b) {
return false
}

const len = a.length;
if (len !== b.length) {
return false;
}

for (var i = 0; i < len; ++i) {
if (a[i] !== b[i]) {
return false;
}
}

return true;
}

const staticOptions = {
fallthrough: false,
setHeaders: setHeaders,
Expand Down Expand Up @@ -166,6 +208,7 @@ function startServer() {
});
server.on('listening', () => {
running = true;
saveSettings();
sendToWindow('started');
logToWindow("server started on port:", local ? "127.0.0.1:" : "::", port, "for path:", root);
});
Expand All @@ -187,6 +230,14 @@ function stopServer() {
}
}

function saveSettings() {
try {
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
} catch (e) {
errorToWindow('ERROR: could not save settings:', e);
}
}

function updateSettings(event, newSettings) {
Object.assign(settings, newSettings);
if (running) {
Expand Down

0 comments on commit f5a7a64

Please sign in to comment.