在electron应用中检测网络

  1. 在创建窗口的webPreferences的配置项中开放node的api
    在这里插入图片描述
  2. 在渲染进程导入node的child_process,关于child_process的信息请移步官网.然后为了显示运行结果我们还需要进行转码,这里用到的是iconv-lite包,下载完毕后按如下设置即可
const child_process = require("child_process");
const iconv = require("iconv-lite");
iconv.skipDecodeWarning = true;
const encodings = "cp936";
const binaryEncoding = "binary";
  1. 执行ping命令
      const ip = 'www.baidu.com';
      const child = child_process.exec(
        "ping " + ip,
        { encoding: binaryEncoding },
        (error, stdout, stderr) => {
          if (error) {
            console.log("ip is inactive.");
            item.checked = false;
            if (this.showCmd) {
              Message.alert("该IP地址暂不可用!", "tip");
            }
            // this.msgList.push(iconv.decode(error, encodings));
            // console.log(iconv.decode(error, encodings));
          } else {
            if (
              this.msgList.some((item) => {
                return item.indexOf("无法访问目标主机") != -1;
              })
            ) {
              item.checked = false;
              if (this.showCmd) {
                Message.alert("该IP地址暂不可用!", "tip");
              }
            } else {
              console.log("ip is active.");
              console.log(iconv.decode(stdout, encodings));
              // console.log(iconv.decode(stderr, encodings));
              item.checked = true;
              if (this.showCmd) {
                Message.alert("该IP地址可用!", "tip");
              }
            }
          }
        }
      );

exec的回调参数中的三个形参分别是运行命令出错的信息error,标准输出stdout,标准错误stderr.
一般说来,普通的错误例如超时、找不到主机名都会被error拿到,但是无法访问目标主机这个错误是不会被error捕捉到的,它会在stdout中。所以我这里用了一个蠢方法,就是分割判断是否有这个字符串,目前我不知道还有啥方法。

  1. 可能有的人想显示运行过程,而不是运行完毕后一次性打印,这里就需要对stdoutstderr进行监听了
child.stdout.on("data", (data) => {
       // console.log(iconv.decode(data, encodings));
       this.msgList.push(iconv.decode(data, encodings));
     });
     child.stderr.on("data", (err) => {
       item.checked = false;
       // console.log("stderr 输出:", iconv.decode(err, encodings));
       this.msgList.push(iconv.decode(err, encodings));
     });
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值