diff options
author | 0neGal <mail@0negal.com> | 2023-01-12 19:33:49 +0100 |
---|---|---|
committer | 0neGal <mail@0negal.com> | 2023-01-12 19:34:39 +0100 |
commit | 2889b310c18acc5fbc926d63659a624e4675fe57 (patch) | |
tree | 265bef0435d71d7c0bbc79f05962d7f6e7bf5e95 /src/modules | |
parent | a67040498d238c3d7b1b947f7be02034f3b71d52 (diff) | |
download | Viper-2889b310c18acc5fbc926d63659a624e4675fe57.tar.gz Viper-2889b310c18acc5fbc926d63659a624e4675fe57.zip |
added: src/modules/json.js
This module makes it easier to read JSON files, simply returning false
on errors, and attempting to repair the JSON automatically.
Diffstat (limited to 'src/modules')
-rw-r--r-- | src/modules/json.js | 35 | ||||
-rw-r--r-- | src/modules/settings.js | 10 |
2 files changed, 39 insertions, 6 deletions
diff --git a/src/modules/json.js b/src/modules/json.js new file mode 100644 index 0000000..5c099b1 --- /dev/null +++ b/src/modules/json.js @@ -0,0 +1,35 @@ +const fs = require("fs"); +const repair = require("jsonrepair"); + +function read(file) { + let json = false; + + // make sure the file actually exists + if (! fs.existsSync(file)) { + return false; + } + + // make sure we're actually reading a file + if (! fs.statSync(file).isFile()) { + return false; + } + + // read the file + let file_content = fs.readFileSync(file, "utf8"); + + // attempt to parse it + try { + json = JSON.parse(file_content); + }catch(err) { + // attempt to repair then parse + try { + json = JSON.parse(repair(file_content)); + }catch(repair_err) { + return false; + } + } + + return json; +} + +module.exports = read; diff --git a/src/modules/settings.js b/src/modules/settings.js index a24f1e0..d0a2db1 100644 --- a/src/modules/settings.js +++ b/src/modules/settings.js @@ -2,6 +2,7 @@ const fs = require("fs"); const path = require("path"); const app = require("electron").app; +const json = require("./json"); const lang = require("../lang"); var invalid_settings = false; @@ -28,17 +29,14 @@ var settings = { // Creates the settings file with the base settings if it doesn't exist. if (fs.existsSync("viper.json")) { - let conf = fs.readFileSync("viper.json", "utf8"); - let json = "{}"; + let conf = json("viper.json"); // Validates viper.json - try { - json = JSON.parse(conf); - }catch (e) { + if (! conf) { invalid_settings = true; } - settings = {...settings, ...json}; + settings = {...settings, ...conf}; settings.zip = path.join(settings.gamepath + "/northstar.zip"); let args = path.join(settings.gamepath, "ns_startup_args.txt"); |