Skip to content

Instantly share code, notes, and snippets.

@ralt
Forked from rlemon/port-checker.js
Last active August 29, 2015 14:00
Show Gist options
  • Save ralt/5a6b40b00ae204d8f5e2 to your computer and use it in GitHub Desktop.
Save ralt/5a6b40b00ae204d8f5e2 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);
};
var net = require('net'),
timeout = 500;
module.exports.checkOpen = function(port, cb) {
return new Promise(function(resolve) {
var open = false,
checked = false,
tid, conn;
var onClose = function() {
if( checked ) return;
checked = true;
clearTimeout(tid);
delete conn;
resolve(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