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/json.js | |
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/json.js')
-rw-r--r-- | src/modules/json.js | 35 |
1 files changed, 35 insertions, 0 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; |