How can I test that a service is listening on TCP with Node.js?
Problem
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?
Solution
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
Discussion
View additional discussion.