-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
54 lines (50 loc) · 1.43 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const url = require('url');
const Promise = require('bluebird');
const net = require('net');
Promise.config({
cancellation: true
});
async function checkInternetConnected (config = {}) {
const { timeout = 5000, retries = 5, domain = 'https://apple.com' } = config;
// eslint-disable-next-line node/no-deprecated-api
const urlInfo = url.parse(domain);
if (urlInfo.port === null) {
if (urlInfo.protocol === 'ftp:') {
urlInfo.port = '21';
} else if (urlInfo.protocol === 'http:') {
urlInfo.port = '80';
} else if (urlInfo.protocol === 'https:') {
urlInfo.port = '443';
}
}
const defaultPort = Number.parseInt(urlInfo.port || '80');
const hostname = urlInfo.hostname || urlInfo.pathname;
for (let i = 0; i < retries; i++) {
const connectPromise = new Promise(function (resolve, reject, onCancel) {
const client = new net.Socket();
client.connect({ port: defaultPort, host: hostname }, () => {
client.destroy();
resolve(true);
});
client.on('data', (data) => {
});
client.on('error', (err) => {
client.destroy();
reject(err);
});
client.on('close', () => {
});
onCancel(() => {
client.destroy();
});
});
try {
return await connectPromise.timeout(timeout);
} catch (ex) {
if (i === (retries - 1)) {
throw ex;
}
}
}
}
module.exports = checkInternetConnected;