Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active March 9, 2019 18:10
Show Gist options
  • Save rauschma/e0aaf04481aff13330e123e2abbec58f to your computer and use it in GitHub Desktop.
Save rauschma/e0aaf04481aff13330e123e2abbec58f to your computer and use it in GitHub Desktop.
async function listenRepeatedly(entity: string, server: Server, port: number) {
for (let i=0; i<10; i++) {
const currentPort = port + i;
try {
await listenOnce(server, currentPort);
console.log(`${entity}: listening at port ${currentPort}.`);
return;
} catch (err) {
if (err.code === 'EADDRINUSE') {
console.log(`${entity}: port ${currentPort} in use, trying next port...`);
server.close();
} else {
throw err;
}
}
}
}
function listenOnce(server: Server, port: number) {
return new Promise((resolve, reject) => {
const listeningListener = () => {
server.removeListener('error', errorListener);
resolve();
};
const errorListener = (err: NodeJS.ErrnoException) => {
server.removeListener('listening', listeningListener);
reject(err);
};
server.once('listening', listeningListener);
server.once('error', errorListener);
server.listen(port);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment