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.
source share