Skip to content

Commit f265a06

Browse files
committed
simplify windows getPort impl
1 parent 23b6b76 commit f265a06

File tree

1 file changed

+12
-34
lines changed

1 file changed

+12
-34
lines changed

packages/utils/src/get-port.ts

Lines changed: 12 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ const execAsync = promisify(exec);
88
* @returns The port number that the process is listening on, or undefined if the process is not listening on any port.
99
*/
1010
export async function getPort(): Promise<number | undefined> {
11-
const pid = process.pid;
12-
const platform = process.platform;
11+
const { pid, platform } = process;
1312

1413
let port: number | undefined;
1514

@@ -20,47 +19,26 @@ export async function getPort(): Promise<number | undefined> {
2019
case 'darwin': {
2120
// Grab the first port entry reported
2221
const result = await execAsync(
23-
`lsof -i -P -n | grep -w ${pid} | grep LISTEN | awk '{print $9}' | sed 's/.*://' | head -n 1`
22+
`lsof -a -i -P -n -p ${pid} | awk '/LISTEN/ {split($9,a,":"); print a[length(a)]; exit}'`
2423
);
2524
port = parseInt(result.stdout.trim(), 10);
2625
break;
2726
}
2827
case 'win32': {
29-
const result = await execAsync(`netstat -ano`);
30-
const lines = result.stdout.trim().split('\n');
31-
const ports: number[] = [];
32-
33-
for (const line of lines) {
34-
const parts = line.trim().split(/\s+/);
35-
36-
if (
37-
parts.length >= 5 &&
38-
parts[3] === 'LISTENING' &&
39-
parts[4] === pid.toString()
40-
) {
41-
const localAddress = parts[1];
42-
const portMatch = localAddress.match(/:(\d+)$/);
43-
44-
if (portMatch?.[1]) {
45-
const foundPort = parseInt(portMatch[1], 10);
46-
if (!Number.isNaN(foundPort)) {
47-
ports.push(foundPort);
48-
}
49-
}
50-
}
51-
}
52-
53-
// Return the lowest port for consistency
54-
if (ports.length > 0) {
55-
port = Math.min(...ports);
56-
}
28+
const result = await execAsync(
29+
`netstat -ano | awk "/LISTENING/ && /${pid}/ {split($2,a,\":\"); print a[length(a)]; exit}"`
30+
);
31+
port = parseInt(result.stdout.trim(), 10);
5732
break;
5833
}
5934
}
60-
} catch {
61-
// Unavailable (e.g. Serverless environments)
35+
} catch (error) {
36+
// In dev, it's helpful to know why detection failed
37+
if (process.env.NODE_ENV === 'development') {
38+
console.debug('[getPort] Detection failed:', error);
39+
}
6240
return undefined;
6341
}
6442

65-
return Number.isNaN(port) ? undefined : port;
43+
return port || undefined;
6644
}

0 commit comments

Comments
 (0)