2017-05-26 209 views
3

我想使用node.js ping本地網絡中的主機。這裏是我的代碼:Ping通過使用Node.Js不斷ping CMD

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

+0

'setInterval'會訣竅 – Jorg

+0

@Jorg,我試過了,但結果如上圖(編輯2) – Zhumpex

+0

我將它包裹在foreach上,而不是間隔(你正在設置一個間隔爲每個主機)。或圍繞整個事情,這取決於你想讓你的變量生存的地方 – Jorg

回答

1

那麼明顯的答案是這樣的:

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陣列每秒一次在每臺主機。

+0

感謝您的解決方案:-) – Zhumpex

+0

@Zhumpex爲您工作? – Clonkex

+1

是的,它像我想要的那樣工作 – Zhumpex