The error Error: listen EADDRINUSE: address already in use occurs when the address or port your Node.js server is trying to bind to is already in use. Here are the steps to resolve this issue.
First, identify which process is using the port. You can do this by running the following command in your terminal:
lsof -i :[port_number]
Replace [port_number]
with the actual port number your server is trying to use. This command will list the process ID (PID) using the port.
Once you have the PID, terminate the process using:
kill -9 [PID]
Replace [PID]
with the actual process ID. This will free up the port.
Sometimes, the process might be a zombie or orphaned process. To list all Node.js processes, use:
ps aux | grep node
Identify any unwanted processes and terminate them using the kill -9
command.
If you don't want to terminate the process or need a quick fix, you can change the port your Node.js server is listening on. Modify your server setup to use a different port:
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
To make your application more robust, you can add error handling for port conflicts:
const server = app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
server.on('error', (error) => {
if (error.code === 'EADDRINUSE') {
console.error(`Port ${PORT} is already in use.`);
process.exit(1);
} else {
throw error;
}
});
For more information on handling this error, you can refer to the following resources: