如何在 node.js、electron 中检查互联网连接

g.d*_*per 1 javascript node.js electron

我正在尝试检测 node.js 和电子中的互联网连接。

我的代码每 1 秒通知一次互联网连接。

但我想要的是在连接时显示连接,断开连接 (仅在连接切换时)不是每 1 秒显示一次。

我可以在 node.js 和电子中做到这一点吗?

主文件

const dns = require('dns');

function liveCheck() {
    dns.resolve('www.google.com', function(err, addr){
        if (err) {
            notifier.notify(
                {
                    appName: "com.myapp.id",
                    title: "network error",
                    message: "disconnected",
                    icon:"./facebook.png"
                }
            );
        }


 else{
            console.log("connected");
        }
    });
}

setInterval(function() {
    liveCheck()
     },1000);
Run Code Online (Sandbox Code Playgroud)

Fre*_*iel 5

navigator.onLine 不是可靠的方法。所以我找到了 npm util 来处理这种情况

安装它 npm i check-internet-connected

并使用它

const checkInternetConnected = require('check-internet-connected');

  const config = {
    timeout: 5000, //timeout connecting to each try (default 5000)
    retries: 3,//number of retries to do before failing (default 5)
    domain: 'apple.com'//the domain to check DNS record of
  }

  checkInternetConnected(config)
    .then(() => {
      console.log("Connection available");          
    }).catch((err) => {
      console.log("No connection", err);
    });
Run Code Online (Sandbox Code Playgroud)