Summary: How can I use Node.js to see whether something is listening on a given port?
Details:
I am writing tests for an HTTP-based application in Node.
I've extended Node's http.Server
with util.inherits
, and in the resulting "class" wrap the standard .listen()
functionality in a method of my own called .start()
. This method performs some setup (e.g. connects to MongoDB) and then calls http.Server.listen(port, cb)
when everything is good to go.
My problem: I'd like to write a test that calls .start()
and then checks that the server is, indeed, listening on the specified port. I would like to do this without sending an HTTP request for the server to field. I just want to test that the server is listening.
Unfortunately, I am not familiar with TCP, but given my experience with port scanning and netstat
and things of that nature, I have the impression that something in Node's net package will let me do this. Is this possible?
Use net.connect():
var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('client connected');
client.end();
});
Node.JS documentation on net
module
I don't know what node.js offers, but here's a way to test if something is listening on a port without establishing a connection to it:
This technique is often referred to as half-open scanning, because you don't open a full TCP connection. You send a SYN packet, as if you are going to open a real connection and then wait for a response. A SYN/ACK indicates the port is listening (open), while a RST (reset) is indicative of a non-listener.
This comes from the nmap port scanning tool, and if you are interested in low-level TCP/IP stuff, there's a lot more to find on its website.
Why? You only care if something is listening if you want to connect to it. So, connect to it, and handle the error. "Don't test, use." This applies to any resource. The best way to test whether it is available is to try to use it.