Ping Continuously Like Ping in CMD Using Node.Js

Viewed 5757

I want use node.js to ping host in local network. Here is my code :

var ping = require('ping');

var host2 = ['192.168.0.1', '192.168.1.2', '192.168.2.3'];

host2.forEach(function(host){
    ping.sys.probe(host, function(active){
        var info = active ? 'IP ' + host + ' = Active' : 'IP ' + host + ' = Non-Active';
        console.log(info);
    });
});

This code only run (ping) once. All I want is to ping continuously. Is this possible with node.js?

EDIT : When I run the code :

enter image description here

EDIT 2 : When using setInterval / setTimeout :

Code :

var ping = require('ping');

var host2 = ['192.168.0.1', '192.168.1.2', '192.168.2.3'];

host2.forEach(function(host){
    ping.sys.probe(host, function tes(active){
        var info = active ? 'IP ' + host + ' = Active' : 'IP ' + host + ' = Non-Active';
        console.log(info);
    });
    setInterval(tes, 2000);
});

Result :

enter image description here

2 Answers

Now you can use async await for the ping module, please find it below -

const ping = require( 'ping' ),
    host = 'www.google.com';


( async () => {

    try {
        const isAlive =  await ping.promise.probe(host, { timeout: 10 });
        const msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
        console.log(msg);
    } catch ( error ) {
        console.log(error, "asassas")
    }

} )()
Related