forked from skoranga/node-connection-tester
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (83 loc) · 2.81 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
var net = require('net'),
util = require('util'),
path = require('path'),
shell = require('shelljs');
var SOCKET_TIMEOUT = 1000; //Setting 1s as max acceptable timeout
function testSync(host, port, connectTimeout) {
var output,
nodeBinary = process.execPath,
scriptPath = path.join(__dirname, "./scripts/connection-tester"),
cmd = util.format('"%s" "%s" %s %s %s', nodeBinary, scriptPath, host, port, connectTimeout);
var shellOut = shell.exec(cmd, {silent: true});
output = {
success: false,
error: null
};
if (shellOut) {
if (shellOut.code === 0) {
if (shellOut.stdout === 'true') {
output.success = true;
} else {
output.error = shellOut.stdout;
}
} else {
output.error = shellOut.stdout;
}
} else {
output.error = "No output from connection test";
}
return output;
}
function testAsync(host, port, connectTimeout, callback) {
var socket = new net.Socket();
var output = {
success: false,
error: null
};
socket.connect(port, host);
socket.setTimeout(connectTimeout);
//if able to establish the connection, returns `true`
socket.on('connect', function () {
socket.destroy();
output.success = true;
return callback(null, output);
});
//on connection error, returns error
socket.on('error', function (err) {
socket.destroy();
output.error = err && err.message || err;
return callback(err, output);
});
//on connection timeout, returns error
socket.on('timeout', function (err) {
socket.destroy();
output.error = err && err.message || err || 'socket TIMEOUT';
return callback(err, output);
});
}
exports = module.exports = {
timeout: function (socketTimeout) {
if (!!socketTimeout) {
SOCKET_TIMEOUT = socketTimeout;
}
return SOCKET_TIMEOUT;
},
test: function ConnectionTester(host, port, callbackOrConnectTimeout, callback) {
// for backward compatibility
if (typeof callbackOrConnectTimeout === 'function'){
console.log('deprecated: Please migrate to the new interface ConnectionTester\(host, port, timeout, callback\)');
return testAsync(host, port, SOCKET_TIMEOUT, callbackOrConnectTimeout);
}
if (typeof callbackOrConnectTimeout === 'number'){
if (callback) {
return testAsync(host, port, callbackOrConnectTimeout, callback);
} else {
return testSync(host, port, callbackOrConnectTimeout);
}
}
if (callbackOrConnectTimeout === undefined){
return testSync(host, port, SOCKET_TIMEOUT);
}
}
};