How to check internet connection status in NodeJs with example
Nodejs Is a javascript environment for Running applications on Desktop and IoT devices.
Sometimes, We need to check internet connection is available in IoT Rasberry PI devices.
There are multiple ways we can check the internet network connection in Nodejs. You can also check other posts on npm command deprecate option is deprecated and Fix for digital envelope routines::unsupported
navigator.onLine gives the status of the internet connection in a browser. But It does not give an accurate result.
if (navigator.onLine) {
console.log('Internet is up');
} else {
console.log('Internet is down');
}
So, Let’s see different ways to check internet connection is up.
How to detect the Internet connection is offline in Nodejs?
NodeJS has an inbuilt dns
module for the domain name system(DNS) for IP address lookup and name resolution.
It provides a lookup() function to check name resolution.
using the callback function, We can find whether the internet is online or offline.
Here is an example code to check the internet connection status in the NodeJS example
let dns = require("dns");
function isInternetOnline(callback) {
dns.lookup("twitter.com", function (error) {
if (error && error.code == "ENOTFOUND") {
callback(false);
} else {
callback(true);
}
});
}
isInternetOnline(function (isOnline) {
if (isOnline) {
console.log("internet connection status is online");
} else {
console.log("internet connection status is offline");
}
});
It gives output below the output
the internet connection status is online
how to check internet connectivity in node.js?
The easiest way to check whether internet connectivity is up or not using the is-online
npm library.
With this library, Can check using server-side nodejs and client browser.
First, Install the is-online library.
npm i is-online
It is easy to get a status using the below line of code
import isOnline from 'is-online';
console.log(await isOnline());