可以在javascript中ping一个ip地址:以下是自定义的实现函数:function Pinger_ping(ip, callback) { if(!this.inUse) {this.inUse = true this.callback = callbackthis.ip = ip var _that = this this.img = new Image() this.img.onload = function() {_that.good()} this.img.onerror = function() {_that.good()} this.start = new Date().getTime() this.img.src = "http://" + ip this.timer = setTimeout(function() { _that.bad()}, 1500)}}用法如下:传入ip和callback参数:比如192.0.8.10 和 mycallBacksetTimeout的返回值就可以判断了。let ping = require('child_process').spawn('ping',['127.0.0.1'])
let iconv = require('iconv-lite')
ping.stdout.on('data',data=>{
let str = iconv.decode(data,'cp936')
console.log(str)
})
ping.stderr.on('data',data=>{
console.log(data)
})
ping.on('close',code=>{
console.log('Ping 结束')
})
//之前是通过exec 来调用,不过当时没有进行测试,想当然的认为是可以的,抱歉。
//以上引入iconv-lite 是为了解码中文