Installed NodeJS on Raspberry Pi, is there a way to check if the rPi is connected to the internet via NodeJs ?
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 } });
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.
addEventListener("offline", (event) => { const statusDisplay = document. getElementById("status"); statusDisplay. textContent = "OFFline"; }); window. addEventListener("online", (event) => { const statusDisplay = document.
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.
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').
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With