How to fix Error: listen EADDRINUSE while using no

2018-12-31 10:22发布

If I run a server with the port 80, and I try to use xmlHTTPrequest i get this error: Error: listen EADDRINUSE

Why is it problem for nodejs, if I want to do a request, while I run a server on the port 80? For the webbrowsers it is not a problem: I can surf on the internet, while the server is running.

The server is:

  net.createServer(function (socket) {
    socket.name = socket.remoteAddress + ":" + socket.remotePort;
    console.log('connection request from: ' + socket.remoteAddress);
    socket.destroy();
  }).listen(options.port);

And the request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    sys.puts("State: " + this.readyState);

    if (this.readyState == 4) {
        sys.puts("Complete.\nBody length: " + this.responseText.length);
        sys.puts("Body:\n" + this.responseText);
    }
};

xhr.open("GET", "http://mywebsite.com");
xhr.send();

30条回答
浮光初槿花落
2楼-- · 2018-12-31 10:59

The error EADDRINUSE (Address already in use) reports that there is already another process on the local system occupying that address / port.

There is a npm package called find-process which helps finding (and closing) the occupying process.

Here is a little demo code:

const find = require('find-process')

const PORT = 80

find('port', PORT)
.then((list) => {
  console.log(`Port "${PORT}" is blocked. Killing blocking applications...`)
  const processIds = list.map((item) => item.pid)
  processIds.forEach((pid) => process.kill(pid, 10))
})

I prepared a small sample which can reproduce the EADDRINUSE error. If you launch the following program in two separate terminals, you will see that the first terminal will start a server (on port "3000") and the second terminal will close the already running server (because it blocks the execution of the second terminal, EADDRINUSE):

Minimal Working Example:

const find = require('find-process')
const http = require('http')

const PORT = 3000

// Handling exceptions
process.on('uncaughtException', (error) => {
  if (error.code === 'EADDRINUSE') {
    find('port', PORT)
      .then((list) => {
        const blockingApplication = list[0]
        if (blockingApplication) {
          console.log(`Port "${PORT}" is blocked by "${blockingApplication.name}".`)
          console.log('Shutting down blocking application...')
          process.kill(blockingApplication.pid)
          // TODO: Restart server
        }
      })
  }
})

// Starting server
const server = http.createServer((request, response) => {
  response.writeHead(200, {'Content-Type': 'text/plain'})
  response.write('Hello World!')
  response.end()
})

server.listen(PORT, () => console.log(`Server running on port "${PORT}"...`))
查看更多
泛滥B
3楼-- · 2018-12-31 11:00

EADDRINUSE means that the port(which we try to listen in node application) is already being used. In order to overcome, we need to identify which process is running with that port.

For example if we are trying to listen our node application in 3000 port. We need to check whether that port is already is being used by any other process.

step1:

$sudo netstat -plunt |grep :3000

That the above command gives below result.

tcp6       0      0 :::3000                 :::*                    LISTEN      25315/node

step2:

Now you got process ID(25315), Kill that process.

kill -9 25315

step3:

npm run start

Note: This solution for linux users.

查看更多
冷夜・残月
4楼-- · 2018-12-31 11:01

This works for me (I'm using mac). Run this command

lsof -PiTCP -sTCP:LISTEN

This's going to display a list of ports that your syetem is using. Find the PID that your node is running

COMMAND     PID          USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node      17269 hientrq   16u  IPv6 0xc42959c6fa30c3b9      0t0  TCP *:51524 (LISTEN)
node      17269 hientrq   19u  IPv4 0xc42959c71ae86fc1      0t0  TCP localhost:1337 (LISTEN)

and run kill -9 [YOUR_PID]

查看更多
人间绝色
5楼-- · 2018-12-31 11:02

** BEFORE DOWNVOTING - Please READ the answer. IT IS RELEVANT! If you are going to downvote this, leave a comment why you think it isn't relevant.


Just a head's up, Skype will sometimes listen on port 80 and therefore cause this error if you try to listen on port 80 from Node.js or any other app.

You can turn off that behaviour in Skype by accessing the options and clicking Advanced -> Connection -> Use port 80 (Untick this)

Turn off Skype port 80 usage

查看更多
不再属于我。
6楼-- · 2018-12-31 11:03

EADDRINUSE means that the port number which listen() tries to bind the server to is already in use.

So, in your case, there must be running a server on port 80 already.

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

You should check for the listening event like this, to see if the server is really listening:

var http=require('http');

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

server.on('listening',function(){
    console.log('ok, server is running');
});

server.listen(80);
查看更多
梦该遗忘
7楼-- · 2018-12-31 11:03

On Debian i found out to run on port 80 you need to issue the command as root i.e

sudo node app.js

I hope it helps

查看更多
登录 后发表回答