In this tutorial, we will explore different methods to check for internet connectivity.
When developing Node.js applications that interact with the internet, it’s crucial to ensure that there is an active internet connection.
Using the is-online
Library
The is-online
library provides a simple way to check for internet connectivity in Node.js.
Create a New Node.js Project
If you don’t have a Node.js project set up, create a new directory for your project, navigate to it in the terminal, and run the following command to initialize a new Node.js project:
mkdir check-internet-connectivity cd check-internet-connectivity npm init -y
Install the is-online Library
Install the is-online
package, which is a lightweight module for checking internet connectivity in Node.js applications:
npm install is-online
Create a JavaScript File
Create a new JavaScript file (e.g., checkInternet.js
) to write your internet connectivity checking logic.
// checkInternet.js const isOnline = require('is-online'); async function checkInternetConnectivity() { try { const online = await isOnline(); if (online) { console.log('Connected to the internet.'); } else { console.log('No internet connection.'); } } catch (error) { console.error('Error checking internet connectivity:', error.message); } } checkInternetConnectivity();
Run the Script
Open your terminal command prompt and execute the below command to run the above code
node checkInternet.js
You should see the output indicating whether your Node.js application is connected to the internet or not.
Integrate into Your Application
In a real-world scenario, you might want to integrate this check into your application logic. For example, you can use it before making API calls or performing other network-dependent tasks.
// Your application logic async function performNetworkTask() { const online = await isOnline(); if (online) { // Perform your network-dependent task here console.log('Performing network task...'); } else { console.log('No internet connection. Cannot perform network task.'); } } performNetworkTask();
Now you have a simple way to check for internet connectivity in your Node.js application using the is-online
library. Feel free to customize and integrate this functionality according to your application’s needs.
Using DNS Lookup
A quick and straightforward method is to check if Node can resolve a known domain.
require('dns').lookupService('8.8.8.8', 53, function(err) { if (err) { console.log("No connection"); } else { console.log("Connected"); } });
This method provides a quick response but may not be foolproof in all scenarios.
Improved DNS Lookup
Improving on the DNS lookup method for faster results:
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) { console.log('Connected to the internet.'); } else { console.log('No internet connection.'); } });
This method is faster and avoids errors not related to internet connectivity.
Using HTTP2
An experimental approach using the HTTP2 module:
const http2 = require('http2'); function isConnected() { return new Promise((resolve) => { const client = http2.connect('https://www.google.com'); client.on('connect', () => { resolve(true); client.destroy(); }); client.on('error', () => { resolve(false); client.destroy(); }); }); } isConnected().then(console.log);
This method uses HTTP2 to test internet connectivity, providing a fast and reliable result.
Check-Internet-Connected Library
A simple npm tool to detect internet connection:
npm install check-internet-connected
Usage:
const checkInternetConnected = require('check-internet-connected'); const config = { timeout: 5000, retries: 5, domain: 'google.com', }; checkInternetConnected(config) .then(() => { console.log('Internet available'); }) .catch((error) => { console.log('No internet', error); });
This library provides a configurable and reliable way to check internet connectivity.
Fetch API
Using the Fetch API to test internet connection:
const connected = fetch("https://google.com", { method: "GET", cache: "no-cache", headers: { "Content-Type": "application/json" }, referrerPolicy: "no-referrer", }).then(() => true) .catch(() => false); // Example usage: console.log(await connected);
This method uses a fetch request to check internet connectivity, providing an accurate result without relying on DNS cache.
Choose the method that best fits your application’s needs and integrate it for reliable internet connectivity checks in your Node.js projects.