Check for internet connectivity in NodeJs

后端 未结 10 1720
甜味超标
甜味超标 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.

提交回复
热议问题