Skip to content

Instantly share code, notes, and snippets.

@farskid
Last active December 30, 2018 20:30
Show Gist options
  • Save farskid/71740f99807c529e5048532170b2655f to your computer and use it in GitHub Desktop.
Save farskid/71740f99807c529e5048532170b2655f to your computer and use it in GitHub Desktop.
Express server manage used port
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
// Start the server using managed startup process
startServer()
// Since express is just a wrapper around http and extends the EventEmitter, one can catch the port error using on('error').
function startServer(app, port) {
// process.env props are usually sent as string
port = Number(port);
const server = app
.listen(port, () => {
console.log(`Example app listening on port ${port}!`);
})
.on("error", err => {
if (err.code === "EADDRINUSE") {
server.close();
startServer(app, port + 1);
}
});
}
@nainemom
Copy link

Usually process.env parameters send as string. So it's better that convert port to integer, first.

@farskid
Copy link
Author

farskid commented Nov 17, 2017

Good catch. Updated the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment