From 8cb24408ad39783a2aa378729a45620ff8634d68 Mon Sep 17 00:00:00 2001 From: "Sung, Po Han" Date: Tue, 26 Apr 2022 00:26:44 +0800 Subject: [PATCH] Force HTTP check under corresponding protocols Since URL object with http or https protocol and default port(80 or 443) will not show the port, the port is only assigned to default port 443 when the protocol is neither one of them. --- index.js | 7 ++++--- test.js | 13 +++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 2030255..7dbf175 100644 --- a/index.js +++ b/index.js @@ -38,10 +38,11 @@ const checkHttp = async (url, timeout) => { const getAddress = async hostname => net.isIP(hostname) ? hostname : (await dnsLookupP(hostname)).address; const isTargetReachable = timeout => async target => { + const isHTTP = target.startsWith('https://') || target.startsWith('http://'); const url = new URL(prependHttp(target)); - if (!url.port) { - url.port = url.protocol === 'http:' ? 80 : 443; + if (!url.port && !isHTTP) { + url.port = 443; } let address; @@ -55,7 +56,7 @@ const isTargetReachable = timeout => async target => { return false; } - if ([80, 443].includes(url.port)) { + if (isHTTP) { return checkHttp(url.toString(), timeout); } diff --git a/test.js b/test.js index d1f9d4a..4a92b1b 100644 --- a/test.js +++ b/test.js @@ -1,5 +1,6 @@ import {promisify} from 'util'; import dns from 'dns'; +import http from 'http'; import test from 'ava'; import isReachable from '.'; @@ -26,6 +27,18 @@ test('multiple https urls', async t => { t.true(await isReachable(['https://google.com', 'https://baidu.com'])); }); +test('http server on custom port', async t => { + const server = http.createServer((_, response) => { + response.writeHead(200).end(); + }).listen(8080); + t.true(await isReachable('http://localhost:8080')); + server.close(); +}); + +test('unreachable http server on custom port', async t => { + t.false(await isReachable('http://localhost:8081')); +}); + test('imap host and port', async t => { t.true(await isReachable('imap.gmail.com:995')); });