Skip to content

Instantly share code, notes, and snippets.

@paulgalow
Last active December 31, 2019 07:24
Show Gist options
  • Save paulgalow/9957a5a42e87701a2d41c3f836599d81 to your computer and use it in GitHub Desktop.
Save paulgalow/9957a5a42e87701a2d41c3f836599d81 to your computer and use it in GitHub Desktop.
Check for internet connectivity using HTTP
const { parse } = require("url");
function checkHTTP(url) {
return new Promise((resolve, reject) => {
const { protocol } = parse(url);
const lib = protocol === "https:" ? require("https") : require("http");
const request = lib.get(url, response => {
console.log(`HTTP Status Code:`, response.statusCode);
resolve(response);
});
request.on("error", err => {
console.error(
`Error trying to connect via ${protocol.replace(":", "").toUpperCase()}`
);
reject(err);
});
});
}
@paulgalow
Copy link
Author

Example, how to call that function:

let isOnline;

checkHTTP("https://www.ecosia.org/")
  .then(() => (isOnline = true))
  .catch(() => (isOnline = false))
  .finally(() => console.log({ isOnline }));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment