Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 671
Donald Derek Avatar asked Mar 07 '13 12:03

Donald Derek


People also ask

How do I check my node Internet connection?

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 } });

How do I check my internet connectivity?

Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top. Windows 10 lets you quickly check your network connection status.

How do you check internet is connected or not in JS?

addEventListener("offline", (event) => { const statusDisplay = document. getElementById("status"); statusDisplay. textContent = "OFFline"; }); window. addEventListener("online", (event) => { const statusDisplay = document.

How do I test my internet flutter?

If the result is not empty we call the setstate() function, and change the variable Active Connection to true, other false, Note: If you are want to check on Application initiating, then you have to call the initState() function and inside call the CheckUserConnection Function.


2 Answers

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').

like image 169
robertklep Avatar answered Oct 08 '22 13:10

robertklep


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.

like image 26
Jaruba Avatar answered Oct 08 '22 12:10

Jaruba