-
Notifications
You must be signed in to change notification settings - Fork 28
/
detect-port.js
73 lines (58 loc) · 1.49 KB
/
detect-port.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
'use strict';
const net = require('net');
module.exports = function() {
const args = Array.prototype.slice.call(arguments);
const promise = new Promise((resolve, reject) => {
if (!args.length) {
return reject('wrong number of arguments');
}
const port = parseInt(args[0], 10);
if (isNaN(port)) {
return reject(`wrong type of arguments with: '${args[0]}'`);
}
const loop = port => {
const socket = new net.Socket();
socket.once('error', () => {
socket.removeAllListeners('error');
socket.removeAllListeners('connect');
socket.end();
socket.destroy();
socket.unref();
const server = new net.Server();
server.on('error', () => {
port++;
loop(port);
});
server.listen(port, () => {
server.once('close', () => {
resolve(port);
});
server.close();
});
});
socket.once('connect', () => {
port++;
loop(port);
socket.removeAllListeners('error');
socket.removeAllListeners('connect');
socket.end();
socket.destroy();
socket.unref();
});
socket.connect({
port: port
});
};
loop(port);
});
if (args.length > 1) {
const cb = args[1];
promise.then(data => {
process.nextTick(cb.bind(null, null, data));
}, err => {
process.nextTick(cb.bind(null, err));
});
} else {
return promise;
}
};