-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathw8r.js
More file actions
65 lines (55 loc) · 1.38 KB
/
w8r.js
File metadata and controls
65 lines (55 loc) · 1.38 KB
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
const net = require('net')
const fork = require('child_process').fork
const ignore = ['ENOENT', 'ECONNREFUSED']
module.exports = function (interval, servers, procfile, procargs, procopts, cb) {
const timers = []
if (typeof procopts === 'function') {
cb = procopts
procopts = {}
}
if (typeof procargs === 'function') {
cb = procargs
procargs = []
procopts = []
}
if (!Array.isArray(servers)) {
const [host, port] = servers.split(':')
if (!port) {
servers = [servers]
} else {
servers = [{host, port}]
}
}
const _total = servers.length
let _done = 0
servers.forEach(s => check(interval, timers, s, procfile, procargs, procopts, done))
function done (err) {
++_done
if (err) {
timers.forEach(tid => clearInterval(tid))
_done = _total
return cb(err)
}
if (_done === _total) {
const child = fork(procfile, procargs, procopts)
cb(null, child)
}
}
}
function check (interval, timers, server, procfile, procargs, procopts, cb) {
timers.push(setInterval(checkServer, interval))
function checkServer () {
const client = net
.connect(server, () => {
client.end()
clearInterval(timers.pop())
return cb()
})
.on('error', (err) => {
if (!ignore.includes(err.code)) {
client.end()
return cb(err)
}
})
}
}