How to check if a port is busy in NodeJS?

How to check if a busy port is busy for localhost ?

Is there a standard algorithm? I am thinking of making an http request to this URL and checking if the response status code is 404 .

+8
source share
3 answers

You can try to start the server, whether it be TCP or HTTP, it does not matter. Then you can try to start listening on the port, and if that fails, check if the error code is EADDRINUSE .

 var net = require('net'); var server = net.createServer(); server.once('error', function(err) { if (err.code === 'EADDRINUSE') { // port is currently in use } }); server.once('listening', function() { // close the server if listening doesn't fail server.close(); }); server.listen(/* put the port to check here */); 

With one-time event handlers, you can wrap this in an asynchronous check function.

+13
source

Check out the awesome tcp-port-used node module !

 //Check if a port is open tcpPortUsed.check(port [, host]) //Wait until a port is no longer being used tcpPortUsed.waitUntilFree(port [, retryTimeMs] [, timeOutMs]) //Wait until a port is accepting connections tcpPortUsed.waitUntilUsed(port [, retryTimeMs] [, timeOutMs]) //and a few others! 

I used them for large tasks using gulp watch tasks to detect when my Express server was safely shut down and when it was deployed again.

This will tell you exactly if the port is connected or not (regardless of SO_REUSEADDR and SO_REUSEPORT , as pointed out by @StevenVachon).

The portscanner NPM module will find free and used ports for you within ranges and is more useful if you are trying to find an open port for binding.

+6
source

process.on ('uncaughtException', e => console.log ( Error: A porta ${process.env.PORT} já está em uso! ))

0
source

Source: https://habr.com/ru/post/955071/


All Articles