Checking for internet connection in Node.js
Our client provided us with an on-premises windows server to run our integration. Our integration was working correctly, except when we found some data missing. Their on-premises network sometimes gets disconnected from the internet. Our application is very time sensitive. We did have redundancy built for that. But we wanted to get all data soon after we are connected. The hiccup was connecting with their database after connection loss. For some reason, reconnection took more than 5 mins after coming back online.
Our Solution
We are using PM2 for process management. For us, the simple way to deal with it was to kill the application on internet loss. After the application kills itself, PM2 automatically restarts all the instances. As the process starts, all connections get restored, and we get data as soon as possible. Yes, we could have spent on debugging the connection issue, but this dirty trick works and works great.
// Checks for internet connection in node.js
const dns = require('dns');
const checkInternet = (cb) => {
dns.lookup('google.com', (err) => {
if (err && err.code == "ENOTFOUND") {
console.log('NO INTERNET...');
cb(false);
} else {
cb(true);
}
});
}