Last active
December 30, 2018 20:30
-
-
Save farskid/71740f99807c529e5048532170b2655f to your computer and use it in GitHub Desktop.
Express server manage used port
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
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); | |
} | |
}); | |
} |
Good catch. Updated the gist.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usually process.env parameters send as string. So it's better that convert
port
to integer, first.