使用Node.Js在CMD中连续Ping Ping

时间:2017-05-26 04:20:06

标签: javascript node.js ping

我想使用node.js来ping本地网络中的主机。这是我的代码:

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);
    });
});

此代码仅运行(ping)一次。我只想连续ping。这是可以用node.js吗?

编辑:当我运行代码时:

enter image description here

编辑2:使用setInterval / setTimeout:

代码:

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);
});

结果:

enter image description here

2 个答案:

答案 0 :(得分:2)

显而易见的答案是:

var ping = require('ping');

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

var frequency = 1000; //1 second

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

这将每秒对host2数组中的每个主机执行一次ping操作。

答案 1 :(得分:0)

现在您可以对ping模块使用异步等待,请在下面找到它-

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")
    }

} )()