Skip to content

EADDRINUSE code in express #4808

Closed
Closed

Description

@tarunsinghh
// using nodejs we can write code to retry to listen on port using
const server = http.createServer().listen(3000);
server.on('error',function(err) {
    if (err.code === 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        setTimeout(() => {
            server.close();
            server.listen(3000, 'localhost');
        }, 1000);
    }
});

how to do this same thing in express

const app = require('express')();
app.on('err',function(err) {
console.log('error occured'); // this doesnt work
});

Activity

  1. dougwilson commented on Feb 4, 2022

    @dougwilson
    Contributor

    It would be the same way you do with Node.js, as app.listen() returns the node.js server object. You can also provide app as the first argument to http.createServer().

  2. tarunsinghh commented on Feb 4, 2022

    @tarunsinghh
    Author

    didn't understand this part -> You can also provide app as the first argument to http.createServer(). , code please

  3. dougwilson commented on Feb 4, 2022

    @dougwilson
    Contributor

    const server = http.createServer(app)

  4. tarunsinghh commented on Feb 4, 2022

    @tarunsinghh
    Author

    okay, this part

    app.listen = function listen() {
      var server = http.createServer(this);
      return server.listen.apply(server, arguments);
    };  

    this is request handler only and then whole code looks like

    const app = require('express')();
    const server  = http.createServer(app);
    server.listen(3000);
    server.on('error',function(err) {
        if (err.code === 'EADDRINUSE') {
            console.log('Address in use, retrying...');
            setTimeout(() => {
                server.close();
                server.listen(3000, 'localhost');
            }, 1000);
        }
    });

    Thanks.

  5. locked as resolved and limited conversation to collaborators on Apr 1, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions