Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In nodejs, how do I check if a port is listening or in use

I'll be very specific here in the hope that folks who understand this can edit to rephrase to the general situation.

Currently when you run "node debug", it spawns a process to listen on port 5858. Then in the parent, a connection is attempted to that port.

However if you have another "node debug" session running, currently "node debug" hangs because that port is in use.

Specifically the message you see is:

 $ node debug example/gcd.js 3 5
< debugger listening on port 5858 >
connecting...

Better would be for it to detect that the port is in use (without a connecting to it which might mess up another client that is trying to connect that existing debugger).

Edit: The accepted solution is now in trepan-ni and trepanjs.

See also Node JS - How Can You Tell If A Socket Is Already Open With The Einaros WS Socket Module?

like image 994
rocky Avatar asked Apr 25 '15 02:04

rocky


1 Answers

Use inner http module:

const isPortFree = port =>
  new Promise(resolve => {
    const server = require('http')
      .createServer()
      .listen(port, () => {
        server.close()
        resolve(true)
      })
      .on('error', () => {
        resolve(false)
      })
  })
like image 56
Terry Su Avatar answered Sep 21 '22 09:09

Terry Su