-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathget-random-port.js
More file actions
105 lines (82 loc) · 2.13 KB
/
get-random-port.js
File metadata and controls
105 lines (82 loc) · 2.13 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
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
101
102
103
104
105
const net = require('node:net');
const minRandomPort = 15000;
const maxRandomPort = 45000;
async function isPortAvailable(port, host = '0.0.0.0') {
try {
const server = net.createServer();
server.unref();
return await new Promise((resolve) => {
server.on('listening', () => {
server.close(() => {
resolve(true);
});
});
server.on('error', () => {
resolve(false);
});
server.listen(port, host);
});
} catch {
return false;
}
}
const portMap = new Map();
function getDefaultPort() {
return Math.ceil(Math.random() * 30000) + minRandomPort;
}
async function findAvailablePort(startPort, count, host) {
let port = Math.max(startPort, minRandomPort);
const maxStartPort = maxRandomPort - count + 1;
while (port <= maxStartPort) {
let isAvailable = true;
for (let index = 0; index < count; index += 1) {
const currentPort = port + index;
if (
portMap.get(currentPort) ||
!(await isPortAvailable(currentPort, host))
) {
isAvailable = false;
break;
}
}
if (isAvailable) {
return port;
}
port += 1;
}
throw new Error('No available ports found');
}
/**
* Get a random port.
* Available port ranges: 1024 ~ 65535
* `10080` is not available on macOS CI, `> 50000` gets "permission denied" on Windows,
* so we use `15000` ~ `45000`.
*/
async function getRandomPort(defaultPort = getDefaultPort(), host) {
const port = await findAvailablePort(defaultPort, 1, host);
portMap.set(port, 1);
return port;
}
async function getRandomPorts(count, host) {
if (count < 1) {
throw new Error('Port count must be greater than 0');
}
const port = await findAvailablePort(getDefaultPort(), count, host);
const ports = [];
for (let index = 0; index < count; index += 1) {
const currentPort = port + index;
portMap.set(currentPort, 1);
ports.push(currentPort);
}
return ports;
}
function releaseRandomPorts(ports = []) {
for (const port of ports) {
portMap.delete(port);
}
}
module.exports = {
getRandomPort,
getRandomPorts,
releaseRandomPorts,
};