Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How can I test that a service is listening on TCP with Node.js?

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?

Problem courtesy of: Dmitry Minkovsky

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

Solution courtesy of: ssafejava

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How can I test that a service is listening on TCP with Node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×