As I write a program that listen on a port, lets say 8081, and then write another program that listen on the same port I will get this type of error message:
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at Server.listen (net.js:1127:5)
at Object.<anonymous> (C:\NetBeansWorkPlace\nodeJS_Files\TutsNodeJS\static_file_server.js:36:4)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
I found that the port is in use but how can I clear the port, or stop the app from listening on a given port?
The server. close() method stops the HTTP server from accepting new connections. All existing connections are kept.
Method 1: Using ctrl+C key: When running a program of NodeJS in the console, you can close it with ctrl+C directly from the console with changing the code shown below: Method 2: Using process. exit() Function: This function tells Node. js to end the process which is running at the same time with an exit code.
Simplest approach is you can change the port number in your javascript file.
If you want to close the port simply do this (solution is for mac) open terminal
1) sudo lsof -i :
a table will be displayed look for PID in this table for your port
2) sudo kill -9 PID
If you want that your node app will automatically close port 8081 before it's further processes start, you can use this trick.
Install the dependency :npm i kill-port
Now, import and run the code given below.
const kill = require("kill-port");
kill(8080, "tcp");
With this, node will first clear the port connection at first so that you can go further with this port. And if the port is not open, then it will cause no harm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With