最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to check internet connectivity in node.js, electron - Stack Overflow

programmeradmin2浏览0评论

I'm trying to detect internet connectivity in node.js and electron.

my code notifies internet connectivity every 1 second.

but what I want is showing connectivity when it's connected, disconnected (only when connection is switched ) not every 1 second.

can I do that in node.js and electron?

main.js

const dns = require('dns');

function liveCheck() {
    dns.resolve('www.google', 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);

I'm trying to detect internet connectivity in node.js and electron.

my code notifies internet connectivity every 1 second.

but what I want is showing connectivity when it's connected, disconnected (only when connection is switched ) not every 1 second.

can I do that in node.js and electron?

main.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);
Share Improve this question edited Mar 11, 2019 at 7:13 g.developer asked Mar 11, 2019 at 6:38 g.developerg.developer 1651 gold badge3 silver badges12 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 5

navigator.onLine is not reliable method. So i found npm util to handle this situation

Install it npm i check-internet-connected

And use it

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

If you were to keep the same logic, you need to add a flag to see if you switched from no connection to connected. I did that with the isConnected flag:

const dns = require("dns");
let isConnected = false;

function liveCheck() {
  dns.resolve("www.google.com", function(err, addr) {
    if (err) {
      if (isConnected) {
        notifier.notify({
          appName: "com.myapp.id",
          title: "network error",
          message: "disconnected",
          icon: "./facebook.png",
        });
      }
      isConnected = false;
    } else {
      if (isConnected) {
        //connection is still up and running, do nothing
      } else {
        notifier.notify({
          appName: "com.myapp.id",
          title: "connection gained",
          message: "connected",
          icon: "./facebook.png",
        });
      }
      isConnected = true;
    }
  });
}

setInterval(function() {
  liveCheck();
}, 1000);

This works for me in the latest Electron version 4.0.8 on macOS, from a renderer process, using only Web API:

function notifyUser (event)
{
    let myNotification = new Notification
    (
        "com.myapp.id",
        { body: (event.type === 'online') ? "Internet available" : "No internet" }
    ); 
}
window.addEventListener ('online', notifyUser, false);
window.addEventListener ('offline', notifyUser, false);

References:

  • navigator.onLine

  • Online and offline events

  • Notification

First, install internet-available package

npm install internet-available  

And then,

var internetAvailable = require("internet-available");

// Set a timeout and a limit of attempts to check for connection
internetAvailable({
    timeout: 4000,
    retries: 10,
}).then(function(){
    console.log("Internet available");
}).catch(function(){
    console.log("No internet");
});
const http2 = require('http2')

const isOnline = () => new Promise((resolve) => {
    const client = http2.connect('https://www.google.com')
    client.on('connect', () => { resolve(true); client.destroy() })
    client.on('error', () => { resolve(false); client.destroy() })
})
发布评论

评论列表(0)

  1. 暂无评论