Check for internet connectivity in NodeJs

2020-02-02 11:12发布

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

7条回答
Emotional °昔
2楼-- · 2020-02-02 11:53

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.

查看更多
登录 后发表回答