-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson-file-mananger.js
55 lines (49 loc) · 1.45 KB
/
json-file-mananger.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const fs = require('fs');
/**
* These are file path global variables for each data.
*/
const LOAD_SHEDDING_MAP_FILE_PATH = './json/loadshedding_map.json';
/**
* Home made function for saving json data to a json file
*/
const saveJSONFile = (jsonData, filePath /** Specify the file path */) => {
// Convert JSON object to string
const jsonString = JSON.stringify(jsonData, null, 2);
let isSaved = false;
// Write the JSON string to a file
fs.writeFile(filePath, jsonString, 'utf8', (err) => {
if (err) {
console.error('Error writing JSON file:', err);
} else {
isSaved = true;
console.log(`JSON file saved successfully at ${filePath}`);
}
});
fs.close();
return isSaved;
}
/**
* Home made function for reading json files...
*/
const fromFileToJSON = filePath => {
let isFound = false;
// Read the JSON file
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) return { isFound, error: `Error reading the file: ${err}` };
try {
// Parse the JSON data
const jsonData = JSON.parse(data);
isFound = true;
// Access the data as needed
return { isFound, jsonData };
} catch (parseError) {
return { isFound, error: `Error parsing JSON: ${parseError}` }
}
});
fs.close();
}
module.exports = {
saveJSONFile,
fromFileToJSON,
LOAD_SHEDDING_MAP_FILE_PATH
};