I am making a monitor which will display to a website if a server is up or down. I have tried numerous things including regex, replacement, etc. when it comes to editing the JSON file. I need the "status" in the JSON file to adjust to up or down based upon the 200 responseCode(the status=up/down is just a placeholder for now). Every time I am able to append the JSON file in anyway the text is always added to the bottom of the page outside of the object. It is important to note that this JSON file is used for the front end in the way that displays a green block if the status is 'up', red if it is 'down.' There are also 11 severs in total in my original JSON file.
const config = require(__dirname + '/config/config.json');
var fs = require('fs');
...
function wrapper() {
//FOR EACH SERVER IN CONFIG FILE
for (var server of config.server) {
var url = server.ip + ':' + server.port;
var name = url + " " + server.name;
// DO REQUEST
loadUrl(url, name);
}
}
function loadUrl(url, name) {
var start = new Date().getTime();
request(url, function(error, response) {
var logName = name.split(' ');
var end = new Date().getTime();
var time = end - start;
if (!error) {
console.log(DateTime + " " + name + " " + response.statusCode + " - response time: " + time + "ms");
var total = DateTime + " " + name + " " + response.statusCode + " - response time: " + time + "ms\n";
fs.appendFile("./BY-logs/" + logDates + "_" + logName[1] + ".txt", total, encoding='utf8', function (err) { if (err) throw err; }); //creating or adding to logfile
//CHANGE JSON ACCORDING TO STATUS
if( response.statusCode != 200) {
fs.appendFile('./config/config.json', status = down, function (err) {});
} else {
fs.appendFile('./config/config.json', status = up, function (err) {});
}
}
}
)};
wrapper();
SAMPLE FROM JSON FILE:
{
"port": 3000,
"server": [{
"id": 1,
"name": "abcdefghi2(node-1)",
"ip": "http://123.123.123.12",
"port": "8080",
"status": "up"
}, {
"id": 2,
"name": "abcdefg(node-2)",
"ip": "http://123.123.123.13",
"port": "8080",
"status": "up"
}]
}
答案 0 :(得分:0)
You need to load the JSON into the program, change the value of the object
, then write it to a file.
Try something along these lines:
var config = require('./config/config.json');
config.server.forEach((server, index, array) => {
if (server.id == "x")
server.status = "up"; // etc.
});
fs.writeFile('./config/config.js', config, (err) => { /* ... */ });
Side note: I would recommened storing your servers as objects inside that object, not an array of objects. This makes it easier to get the server object you want.