Last active
March 9, 2019 18:10
-
-
Save rauschma/e0aaf04481aff13330e123e2abbec58f to your computer and use it in GitHub Desktop.
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
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