1 | import ChildProcess from 'child_process';
|
2 | export function getAvailablePort(defaultPort = 3000) {
|
3 | return new Promise(resolve => {
|
4 | ChildProcess.exec('lsof -i -P -n | grep LISTEN', (error, stdout) => {
|
5 | if (error) {
|
6 | resolve(defaultPort);
|
7 | return;
|
8 | }
|
9 |
|
10 | const portsInUse = [];
|
11 | const regex = /:(\d+) \(LISTEN\)/;
|
12 | stdout.split('\n').forEach(line => {
|
13 | const match = regex.exec(line);
|
14 |
|
15 | if (match) {
|
16 | portsInUse.push(Number(match[1]));
|
17 | }
|
18 | });
|
19 | let port = defaultPort;
|
20 |
|
21 | while (portsInUse.includes(port)) {
|
22 | port++;
|
23 | }
|
24 |
|
25 | resolve(port);
|
26 | });
|
27 | });
|
28 | }
|
29 |
|
\ | No newline at end of file |