I'm trying to write a small program that will ping internal addresses to check if a server is down. The problem is that I cant get the timing right. If I put a console.log() inside the for of loop it returns the objects I want but several times of cource. If I write a console.log after the for of loop, I only get an empty array, probably because the loop is not finished yet.I have tried to fix this in various ways but keep running into problems. I use node-cmd to send an http ping as normal pings only work against domains.
You can ignore my nightmare regex :) It should just split the response into an array which is then pushed to object
var cmd = require('node-cmd');
const hosts = [
'https://adressone.com',
'https://adresstwo.com',
'https://adressthree.com',
'https://adressfour.com'
];
let results = [];
for (let host of hosts) {
cmd.run(`http-ping.exe ${host}`,
async function(err, data, stderr) {
const result = await data.split('>');
const resultDig = result[1].replace(/[^0-9\.]+/g, " ").replace(/2$/g, "").trim().split(' ')
results.push({
host: host,
status: resultDig[0],
bytes: resultDig[1],
time: resultDig[2],
});
}
);
}
console.log(results);
The result I would like in console.log(results):
[{
host: 'https://adressone.com',
status: '200',
bytes: '703',
time: '640'
},
{
host: 'https://adresstwo.com',
status: '200',
bytes: '703',
time: '640'
},
{
host: 'https://adressthree.com',
status: '200',
bytes: '703',
time: '640'
},
{
host: 'https://adressfour.com',
status: '200',
bytes: '703',
time: '640'
}
]
node-cmdpackage does not appear to have a promise variant, you either use thesyncvariant not ideal, or promisify the callback variant, you could thenawaiteach iteration. The problem at the moment is your console logging before it's even done.