Created
June 29, 2016 18:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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