Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Internet test with ping in NodeJS
const ping = require('ping');
let host = '8.8.8.8';
if (process.argv[2]) {
host = process.argv[2];
} else {
console.log("Syntax: \nnode ping-test-ifchanges-host host");
}
console.log("Testing host: " + host);
let isAlivePrev = false;
let nowPrev = new Date();
function doPing() {
ping.sys.probe(host, isAlive => {
if (isAlive !== isAlivePrev) {
let now = new Date();
let diff = (now.getTime() - nowPrev.getTime())/1000;
let timestamp = now.toISOString() + ' after: ' + diff + ' s';
console.log("\n" + host + ': ' + (isAlive ? ' OK' : ' KO') + ' ' + timestamp);
isAlivePrev = isAlive;
nowPrev = now;
} else {
process.stdout.write('.');
}
});
}
setInterval(doPing, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment