-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (37 loc) · 991 Bytes
/
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
'use strict';
const net = require('net');
/**
* Choose an available port
* @param {Number} portInitial Initial port
* @param {String} host Host
* @param {function} callback Callback
*/
const choosePort = (portInitial, host, callback) => {
const server = net.createServer(socket => {
socket.pipe(socket);
});
server.listen(portInitial, host);
server.on('error', () => {
choosePort(portInitial + 1, host, newPort => callback(newPort));
});
server.on('listening', () => {
server.close();
callback(portInitial);
});
};
/**
* Choose async an available port
* @param {Number} portInitial Initial port
* @param {String} host Host
*/
const choosePortSync = (portInitial, host) => {
let port;
choosePort(portInitial, host, newPort => {
port = newPort;
});
require('deasync').loopWhile(() => !port);
return port;
};
module.exports = choosePort;
module.exports.choosePort = choosePort;
module.exports.choosePortSync = choosePortSync;