使用Node.js持续像CMD中的Ping一样进行Ping。

5

我想使用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


setInterval 就能搞定 - Jorg
@Jorg,我已经尝试过了,但结果就像上面所述(编辑2)。 - Zhumpex
我会将它包装在foreach循环周围,这样间隔就会少一些(你为每个主机设置了一个间隔)。或者根据你想让变量存在的位置,将其包装在整个代码块周围。 - Jorg
2个回答

5

显而易见的答案是:

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。


感谢您的解决方案 :-) - Zhumpex

2
现在您可以使用async await来使用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")
    }

} )()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接