Skip to content

Instantly share code, notes, and snippets.

@rmg
Created June 29, 2016 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmg/90f77f6e78517a21996071c31821b955 to your computer and use it in GitHub Desktop.
Save rmg/90f77f6e78517a21996071c31821b955 to your computer and use it in GitHub Desktop.
Wrapper for net.connect to test if a host can be connected to on a given tcp port
'use strict';
var fmt = require('util').format;
var net = require('net');
module.exports = testConnection;
if (require.main !== module) {
return;
}
var host = process.argv[2];
var port = 1 * (process.argv[3] || 80);
var timeout = 1 * (process.argv[4] || 5);
if (timeout < 100) {
// assume given in seconds
timeout = timeout * 1000;
}
testConnection(host, port, timeout, console.log);
function testConnection(host, port, timeout, callback) {
var failure = new Error(fmt('could not connect to: %s:%d within %dms',
host, port, timeout));
var timer = setTimeout(failed, timeout);
var so = net.connect(port, host, connected);
so.setTimeout(timeout, failed);
so.once('error', failed);
return so;
function cleanup() {
if (!so) {
return false;
}
clearTimeout(timer);
so.end();
so.destroy();
so.unref();
so = null;
return true;
}
function connected() {
if (cleanup()) {
callback(null, true);
}
}
function failed(err) {
if (cleanup()) {
callback(err || failure);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment