Skip to content

Instantly share code, notes, and snippets.

@rlemon
Created May 2, 2014 14:40
Show Gist options
  • Save rlemon/594026dcf95479b1409a to your computer and use it in GitHub Desktop.
Save rlemon/594026dcf95479b1409a to your computer and use it in GitHub Desktop.
var net = require('net'),
timeout = 500;
module.exports.checkOpen = function(port, cb) {
var open = false,
checked = false,
tid, conn;
var onClose = function() {
if( checked ) return;
checked = true;
clearTimeout(tid);
delete conn;
cb(open);
};
var onOpen = function() {
open = true;
conn.end();
};
tid = setTimeout(function() {
conn.destroy();
}, timeout);
conn = net.createConnection(port, 'localhost', onOpen);
conn.on('close', function() { if( !checked ) { onClose() }});
conn.on('error', function() { conn.end(); });
conn.on('connect', onOpen);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment