aboutsummaryrefslogtreecommitdiff
path: root/src/modules/json.js
blob: 5c099b1db92575658c0b5d89d18a0c360463afa0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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;