javascript - 使用 Node.Js 在 CMD 中连续 Ping 就像 Ping

标签 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

最佳答案

显而易见的答案是:

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

这将每秒 ping host2 数组中的每个主机一次。

关于javascript - 使用 Node.Js 在 CMD 中连续 Ping 就像 Ping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44193551/

相关文章:

google-chrome - 在网络选项卡中输入 "ping"

java - Tomcat 7.0 启动时抛出错误

python - Scapy ICMPv6EchoRequest 从 Scapy 命令提示符发送,但不是从脚本内发送?

javascript - 返回 JSON 中的 Base64 编码缩略图还是只返回 URL?

javascript - 获取 "contentEditable-Div"中插入符处的所有 Node

javascript - Node 中导入时出现语法错误

javascript - 将变量从服务器端 Controller 传递到客户端以在客户端 JavaScript 中使用

javascript - 是什么阻止了该动画的自动执行?

javascript - ReactJS:根据 axios 发布结果显示红色/绿色背景的状态

javascript - 滚动到窗口调整大小的最左边的元素 - 怎么样?