Permalink
Browse files

Rewrote

  • Loading branch information...
1 parent 9b04dfe commit 3974012f82d8dd4470c0091ea514edb93cf1bd66 @MiguelMadero MiguelMadero committed Oct 10, 2012
Showing with 22 additions and 17 deletions.
  1. +22 −17 lib/network.js
View
@@ -12,29 +12,34 @@ network = new (function () {
@function
@description Checks if the given port in the given host is open
@param {Number} port number
- @param {String} host Defaults to null if not given
- @param {Function} callback
+ @param {String} host
+ @param {Function} callback Callback function -- should be in the format of function(err, result) {}
*/
this.isPortOpen = function (port, host, callback) {
var isOpen = false
- , conn = net.createConnection(port, host)
- , timeoutId = setTimeout(function () { onClose(); }, timeout)
- , timeout = 400;
-
- var onClose = function () {
- clearTimeout(timeoutId);
- delete conn;
- callback(isOpen, port, host);
- };
+ , connection
+ , error;
- var onOpen = function () {
+ connection = net.createConnection(port, host, function () {
isOpen = true;
- conn.end();
- };
+ connection.end();
+ });
- conn.on('close', onClose);
- conn.on('error', function() { conn.end(); });
- conn.on('connect', onOpen);
+ connection.on('error', function (err) {
+ // We ignore 'ECONNREFUSED' as it simply indicates the port isn't open. Anything else is reported
+ if(err.code !== 'ECONNREFUSED') {
+ error = err;
+ }
+ // the socket emits 'close' after 'error'. No need to do anything here
+ })
+
+ connection.setTimeout(400, function () {
+ connection.end();
+ });
+
+ connection.on('close', function (had_error) {
+ callback(error, isOpen);
+ });
};
})();

0 comments on commit 3974012

Please sign in to comment.