Skip to content

Instantly share code, notes, and snippets.

@paulgalow paulgalow/checkHTTP.js
Last active Dec 31, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

paulgalow commented Dec 31, 2019

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
You can’t perform that action at this time.