Skip to content

Commit f97c2dd

Browse files
committed
Create utility func to get a random port
1 parent b3240c8 commit f97c2dd

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/utils.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as path from 'path';
33
import * as fs from "fs";
44
import * as os from "os";
55
import { exec, execSync } from "child_process";
6+
import * as net from 'net';
67

78
export function stripAnsi(input: string): string {
89
const esc = String.fromCharCode(27);
@@ -137,4 +138,21 @@ export function execWithProgress(command: string, progressMessage: string): Then
137138
});
138139
})
139140
);
140-
}
141+
}
142+
143+
export async function getFreePort(): Promise<number> {
144+
return new Promise((resolve, reject) => {
145+
const server = net.createServer();
146+
server.listen(0, '127.0.0.1');
147+
server.on('listening', () => {
148+
const address = server.address();
149+
server.close();
150+
if (typeof address === 'object' && address?.port) {
151+
resolve(address.port);
152+
} else {
153+
reject(new Error('Could not get free port'));
154+
}
155+
});
156+
server.on('error', reject);
157+
});
158+
}

0 commit comments

Comments
 (0)