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();
There are two options to resolve this issue in Windows/Mac
1. Free Port Number
Windows
Mac
You can try netstat
For OSX El Capitan and newer (or if your netstat doesn't support -p), use lsof
if this does not resolve your problem,
Mac
users can refer to complete discussion about this issue Find (and kill) process locking port 3000 on Mac2. Change Port Number?
Windows
Mac
I would prefer doing
killall -15 node
because,
kill -15
gives process a chance to cleanup itself. Now, you can verify byps aux | grep node
Note: If you don't give process a chance to finish what it is currently doing and clean up, it may lead to corrupted files
The option which is working for me :
Run:
You'll get something like:
Your application is already running on that port 8080 . Use this code to kill the port and run your code again
In below command replace your portNumber
The aforementioned
killall -9 node
, suggested by Patrick works as expected and solves the problem but you may want to read the edit part of this very answer about whykill -9
may not be the best way to do it.On top of that you might want to target a single process rather than blindly killing all active processes.
In that case, first get the process ID (PID) of the process running on that port (say 8888):
lsof -i tcp:8888
This will return something like:
Then just do (ps - actually do not. Please keep reading below):
kill -9 57385
You can read a bit more about this here.
EDIT: I was reading on a fairly related topic today and stumbled upon this interesting thread on why should i not
kill -9
a process.So, as stated you should better kill the above process with:
kill -15 57385
EDIT 2: As noted in a comment around here many times this error is a consequence of not exiting a process gracefully. That means, a lot of people exit a node command (or any other) using CTRL+Z. The correct way of stopping a running process is issuing the CTRL+C command which performs a clean exit.
Exiting a process the right way will free up that port while shutting down. This will allow you to restart the process without going through the trouble of killing it yourself before being able to re-run it again.