Created
November 23, 2024 16:28
-
-
Save LeeCheneler/982afdd0b9a87822f236ac09b8b90f42 to your computer and use it in GitHub Desktop.
get next available port from starting port in Deno
This file contains hidden or 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
/** | |
* Get an available port starting from the provided port number. | |
* | |
* @param startPort | |
* @returns | |
*/ | |
export const getAvailablePort = (startPort: number): number => { | |
for (let port = startPort; port < 65535; port++) { | |
try { | |
Deno.listen({ port }).close(); | |
return port; | |
} catch (e) { | |
if (e instanceof Deno.errors.AddrInUse) { | |
continue; | |
} else { | |
throw e; | |
} | |
} | |
} | |
throw new Error("No available ports found"); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment