How to fix Error: listen EADDRINUSE while using NodeJS

This article will show you how to fix Error: listen EADDRINUSE while using NodeJS.

The “EADDRINUSE” error in Node.js means that the port number you’re trying to use is already in use by another process. When a port is already being used, Node.js won’t be able to bind to it for your server.

Now, have a look at the solutions below to fix the error.

Change the Port Number

Use a different port number that is not in use. You can modify the port number your Node.js application listens on.

Suppose, you’re using port 3000 and it’s already in use, try switching to port 4000 or another available port.

const PORT = 4000; // Change to an available port number
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Fixing EADDRINUSE Error by Killing Node.js Processes

When you encounter the EADDRINUSE error in Node.js, it’s usually due to a port conflict. If restarting your server or changing ports doesn’t work, you might need to identify and terminate the Node.js processes holding the port.

Identify Node.js Processes

Run the following command in your terminal to find Node.js processes.

ps ax | grep node

This command displays a list of processes, and grep node filters to only show those related to Node.js.

Terminating the Node.js Processes

If you find Node.js processes using the port and causing conflicts, you can terminate them using the command mentioned below.

killall -9 node

Checking if It Worked

After executing the killall command, you can verify whether the Node.js processes were terminated successfully by rerunning the ps ax | grep node command. If no Node.js processes appear, you’ve successfully cleared the port.

Resolving ‘EADDRINUSE’ Error and Checking Server Listening Status

The ‘EADDRINUSE’ error occurs when the port specified in the listen() function for server binding is already in use.

Suppose you have set up a server on port 80.

If you have another webserver running on this port you have to put node.js behind that server and proxy it through it.

To confirm if the server is genuinely listening on the specified port, you can utilize the ‘listening‘ event in Node.js.

const http = require('http');

const server = http.createServer((req, res) => {
    res.end('test');
});

server.on('listening', () => {
    console.log('The server is now actively listening');
});

server.listen(80);

This code snippet creates a server on the port 80 and logs a message when the listening event occurs, indicating that the server is operational.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top