i am new to nodejs, and i am headache with callback..
i want to write an app that allow users to select and query some device status of the server (e.g. ping, cpu, memory, etc.). The items to be queried will be sent to the backend server though URL. I used a for loop and a switch to call the functions which execute shell commands (eg. ssh, ping, etc) to get server status. Finally i want to write all the result (res.write) to front end.
I failed to make it work, either return null or approach 'write before end' error... please help me.
Here is my code, i tried to simplify it.
app.get('/check', function(req, res, next) {
var selecteditems = req.query.selecteditems; //ping,memory,disks,etc.
checkcon(selecteditems, function(results) {
res.write(JSON.stringify(results), function(err) {
res.end();
});
});
});
var checkcon = function(selecteditems, callback) {
var selecteditems = selecteditems.split(',');
var allresults = [];
selecteditems.forEach(function(entry) {
switch (entry) {
case "ping":
checkping(function(results) {
allresults.push(results);
});
break;
case "memory":
checkmemory(function(results) {
allresults.push(results);
});
break;
case "disks":
checkdisks(function(results) {
allresults.push(results);
});
break;
case "disks":
break
default:
}
callback(allresults);
});
}
example of the one of the function for shell command:
var checkping = function(callback) {
var pingstat = [];
const child = exec('ping -c 1 -W 1 10.102.12.2',
(error, stdout, stderr) => {
if (error !== null) {
console.log(`exec error: ${error}`);
pingstat.push("Unable to ping machine");
} else {
pingstat.push("OK");
}
callback(pingstat);
});
}
checkpingis an async function and you are calling callback before waiting for it to finish. You will need to return a promise for each iteration and use Promise.all to wait for all to finish, and then call the callback function.