user3000938
user3000938

Reputation: 177

close a port with nodeJS

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?

Upvotes: 8

Views: 18011

Answers (4)

user16821381
user16821381

Reputation:

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.

Upvotes: 3

jide olaniyan
jide olaniyan

Reputation: 11

consult this for a better understanding of this tool fuser

fuser -k -n tcp portNumber

Upvotes: 1

Konkret
Konkret

Reputation: 1021

Here are your options:

1- Exit the terminal you ran the node application from

2- Change the port number by editing the application

3- Use forever

4- Kill the process directly

I haven't tried the 4th option, but in theory it should work. Also, there are times when all of the above do not yield. That's where you would, logout, or restart your computer.

Upvotes: 0

Ankit Sachan
Ankit Sachan

Reputation: 7850

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

Upvotes: 4

Related Questions