Check for internet connectivity in NodeJs

Donald Derek picture Donald Derek · Mar 7, 2013 · Viewed 41.5k times · Source

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

Answer

Jaruba picture Jaruba · Feb 25, 2015

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.