Skip to content

How to catch the exception "Port is already used" #3903

Answered by darrachequesne
huuson235 asked this question in Q&A
Discussion options

You must be logged in to vote

You can catch the 'EADDRINUSE' error event:

const httpServer = require("http").createServer();
const io = require("socket.io")(httpServer, { /* ... */ });
const port = 8080;

io.on("connection", (socket) => { /* ... */ });

server.listen(port, () => {
  console.log(`server listening on port ${port}`)
});

server.on("error", (e) => {
  if (e.code === "EADDRINUSE") {
    process.exit(1);
  }
});

Reference: https://nodejs.org/api/net.html#net_server_listen

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by darrachequesne
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants