Node.js Server Errors: How to Handle EADDRINUSE Node.js Server Errors: How to Handle EADDRINUSE

In this article, we'll explore the 'Error: listen EADDRINUSE' error in Node.js, which occurs when a port that a server is trying to use is already in use by another process. We'll delve into the causes of this error and provide various solutions to fix it, including code examples and practical tips to help you overcome this error and keep your Node.js servers running smoothly.


As a Node.js developer, you may have encountered the "Error: listen EADDRINUSE" error at some point in your career. This error can be frustrating and time-consuming to debug, especially if you're not sure what's causing it. But fear not! In this article, we'll dive into the nitty-gritty details of this error and provide you with various solutions to get your server back up and running.

What is the "Error: listen EADDRINUSE" Error?

The "Error: listen EADDRINUSE" error occurs when a server is unable to bind to a specific port because that port is already in use by another process. This can happen for a variety of reasons, including:

- The server was not shut down properly and is still running in the background.

- Another program is using the same port as the server.

- The server is being started too quickly after a previous instance has been closed.

Solutions to the "Error: listen EADDRINUSE" Error:

1. Kill the process using the port:

One solution to this error is to identify the process using the port and kill it manually. Here's an example of how to do that in Node.js:


const net = require('net');
const server = net.createServer();
server.once('error', (err) => {
if (err.code === 'EADDRINUSE') {
const port = parseInt(err.message.split(':').pop(), 10);
console.log(`Port ${port} is already in use`);
const kill = require('tree-kill');
const pid = parseInt(fs.readFileSync(`${port}.pid`));
kill(pid);
server.listen(port, () => {
console.log(`Server started on port ${port}`);
});
}
});

In this example, we're creating a new server and listening on a specific port. If the port is already in use, we're identifying the process using the port and killing it before restarting the server.

2. Change the port number:

Another solution to this error is to simply change the port number that your server is listening on. Here's an example of how to do that in Node.js:


const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World!');
});
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
server.listen(0);
}
});
server.listen(8080, () => {
console.log(`Server started on port ${server.address().port}`);
});

In this example, we're creating an HTTP server and listening on port 8080. If the port is already in use, we're changing the port number by calling the `listen` method with a value of 0, which will assign a random port number.

3. Use a process manager:

Another solution to this error is to use a process manager like PM2, which can automatically restart your server if it crashes or encounters an error. Here's an example of how to use PM2 in Node.js:


npm install pm2 -g
pm2 start app.js

In this example, we're installing PM2 globally using npm and then starting our Node.js application with the `pm2 start` command. PM2 will automatically monitor our application and restart it if it crashes or encounters an error, including the "Error: listen EADDRINUSE" error.

4. Use a unique port:

Finally, another solution to this error is to ensure that the port number your server is listening on is unique and not being used by any other process. Here's an example of how to generate a random port number in Node.js:


const http = require('http');
function getRandomPort() {
const min = 1024;
const max = 65535;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const port = getRandomPort();
const server = http.createServer((req, res) => {
res.end('Hello World!');
});
server.listen(port, () => {
console.log(`Server started on port ${port}`);
});

In this example, we're generating a random port number using the getRandomPort function and then creating an HTTP server and listening on that port. By generating a unique port number, we can avoid the "Error: listen EADDRINUSE" error altogether.

In this article, we've explored the "Error: listen EADDRINUSE" error in Node.js and provided various solutions to fix it. By understanding the causes of this error and implementing these solutions, you can keep your Node.js servers running smoothly and avoid any downtime. Remember to always test your code thoroughly and handle errors gracefully to ensure the best possible user experience.

Published on May 15, 2023

Tags: Node js Tutorial | EADDRINUSE

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.