Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

close a port with nodeJS

Tags:

node.js

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?

like image 553
user3000938 Avatar asked Nov 17 '13 05:11

user3000938


People also ask

How do I stop HTTP server in node JS?

The server. close() method stops the HTTP server from accepting new connections. All existing connections are kept.

How do I close node JS?

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.


2 Answers

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

like image 106
Ankit Sachan Avatar answered Oct 15 '22 21:10

Ankit Sachan


If you want that your node app will automatically close port 8081 before it's further processes start, you can use this trick.

  1. Install the dependency :npm i kill-port

  2. 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.

like image 2
Shuvro Das Avatar answered Oct 15 '22 19:10

Shuvro Das