This repository has been archived by the owner on Jan 2, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c8b4ce1
commit 67e57f5
Showing
2 changed files
with
35 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import net from 'net' | ||
|
||
const MAX_PORT = 65535 // Maximum valid port number | ||
|
||
export const findAvailablePort = async (startPort: number): Promise<number> => { | ||
let port = startPort | ||
|
||
while (port <= MAX_PORT) { | ||
if (!(await isPortInUse(port))) { | ||
return port | ||
} | ||
port++ | ||
} | ||
|
||
throw new Error(`Unable to find an available port in range ${startPort}-${MAX_PORT}`) | ||
} | ||
|
||
const isPortInUse = (port: number): Promise<boolean> => { | ||
return new Promise((resolve) => { | ||
const server = net.createServer() | ||
server.once('error', () => { | ||
resolve(true) | ||
}) | ||
server.once('listening', () => { | ||
server.close() | ||
resolve(false) | ||
}) | ||
server.listen(port) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters