Check for internet connectivity in NodeJs

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

    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.

提交回复
热议问题