node.jsnetwork-programmingraspberry-pi

Check for internet connectivity in NodeJs


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


Solution

  • A quick and dirty way is to check if Node can resolve www.google.com:

    require('dns').resolve('www.google.com', function(err) {
      if (err) {
         console.log("No connection");
      } else {
         console.log("Connected");
      }
    });
    

    This isn't entire foolproof, since your RaspPi can be connected to the Internet yet unable to resolve www.google.com for some reason, and you might also want to check err.type to distinguish between 'unable to resolve' and 'cannot connect to a nameserver so the connection might be down').