Skip to content

Instantly share code, notes, and snippets.

@cptpiepmatz
Last active February 7, 2022 10:56
Show Gist options
  • Save cptpiepmatz/cf0d8e98aae2a93928f68f86c040d2aa to your computer and use it in GitHub Desktop.
Save cptpiepmatz/cf0d8e98aae2a93928f68f86c040d2aa to your computer and use it in GitHub Desktop.
Get free port via Node without packages/dependencies
import {createServer, AddressInfo} from "net";
/**
* Utility function to return a free port.
*
* Uses dummy server that listens to port 0 to let the OS assign the server a
* port.
* Then the server will be closed and the now open port will be returned.
*
* @return by OS assigned, free port
*/
export default async function getFreePort(): Promise<number> {
return new Promise(resolve => {
// dummy server to have the port assigned to
let dummyServer = createServer();
// listening to port 0 will let the OS assign a port
dummyServer.listen(0, () => {
let {port} = dummyServer.address() as AddressInfo;
dummyServer.close(() => {
// after server is closed, the port should be free
resolve(port);
})
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment