Check for internet connectivity in NodeJs

后端 未结 10 1722
甜味超标
甜味超标 2020-12-08 07:10

Installed NodeJS on Raspberry Pi, is there a way to check if the rPi is connected to the internet via NodeJs ?

相关标签:
10条回答
  • 2020-12-08 07:27

    While robertklep's solution works, it is far from being the best choice for this. It takes about 3 minutes for dns.resolve to timeout and give an error if you don't have an internet connection, while dns.lookup responds almost instantly with the error ENOTFOUND.

    So I made this function:

    function checkInternet(cb) {
        require('dns').lookup('google.com',function(err) {
            if (err && err.code == "ENOTFOUND") {
                cb(false);
            } else {
                cb(true);
            }
        })
    }
    
    // example usage:
    checkInternet(function(isConnected) {
        if (isConnected) {
            // connected to the internet
        } else {
            // not connected to the internet
        }
    });
    

    This is by far the fastest way of checking for internet connectivity and it avoids all errors that are not related to internet connectivity.

    0 讨论(0)
  • 2020-12-08 07:27

    It's not as foolproof as possible but get the job done:

    var dns = require('dns');
    dns.lookupService('8.8.8.8', 53, function(err, hostname, service){
      console.log(hostname, service);
        // google-public-dns-a.google.com domain
    });
    

    just use a simple if(err) and treat the response adequately. :)

    ps.: Please don't bother telling me 8.8.8.8 is not a name to be resolved, it's just a lookup for a highly available dns server from google. The intention is to check connectivity, not name resolution.

    0 讨论(0)
  • 2020-12-08 07:32

    Since I was concerned with DNS cache in other solutions here, I tried an actual connectivity test using http2. I think this is the best way to test the internet connection as it doesn't send much data and also doesn't rely on DNS resolving alone and it is quite fast.

    Note that this was added in: v8.4.0

    const http2 = require('http2');
    
    function isConnected() {
      return 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();
        });
      });
    };
    
    isConnected().then(console.log);
    

    Edit: I made this into a package if anyone is interested.

    0 讨论(0)
  • 2020-12-08 07:37

    I found a great and simple npm tool to detect internet connection. It's looks like more reliable.

    First you need to install npm i check-internet-connected

    Then you can call it like follows

      const checkInternetConnected = require('check-internet-connected');
    
      const config = {
        timeout: 5000, //timeout connecting to each server(A and AAAA), each try (default 5000)
        retries: 5,//number of retries to do before failing (default 5)
        domain: 'google.com'//the domain to check DNS record of
      }
    
      checkInternetConnected(config)
        .then(() => {
          console.log("Internet available");          
        }).catch((error) => {
          console.log("No internet", error);
        });
    
    0 讨论(0)
提交回复
热议问题