0

My end goal is to use express on nodejs to try listening on port X ... but if port X is in use, try on port X+1 ... lather, rinse, repeat until we find an open port. I seem unable to catch an error or an emitted event.

My nodjs code looks like this:

const express = require('express');
const app = express();
var listeningPort = 3000;
app.listen(listeningPort, () => {console.log("Listening to " + listeningPort)})
    .on('error', function(err) { console.log('"HERE IS THE ERROR" :>> ', err); });

When I run this code in two separate windows on node, the second startup throws an error and does NOT output "HERE IS THE ERROR". The code does continue to 'run' though (node doesn't exit)

Further, if I try to wrap the .listen code in a try-catch, the catch doesn't actively catch the error either. (and node actually exists, just as if I didn't have a try-catch involved)

Here are some background questions that indicate why the normal try-catch pattern doesn't work (the try completes before the error is thrown)... and they indicate the above emitted error should work.

How do I catch node.js/express server errors like EADDRINUSE?

Node.js Express app handle startup errors

https://github.com/expressjs/express/issues/2856

Any thoughts on how I can catch this error so I can re-run the .listen function with a different port?

lowcrawler
  • 6,777
  • 9
  • 37
  • 79
  • Does this help by any chance?? https://stackoverflow.com/questions/22262128/node-httpserver-eaddrinuse-and-next-port – NullDev Sep 19 '20 at 16:28
  • use `error.code` to get `EADDRINUSE` error – aRvi Sep 19 '20 at 16:34
  • @aRvi -- the `on('error'....` never even gets called. Once I get it to react to the `on('error`..` event, then I can parse what I need. – lowcrawler Sep 19 '20 at 21:25

0 Answers0