Last active
February 3, 2018 19:48
-
-
Save apocas/5701011 to your computer and use it in GitHub Desktop.
Node,js SSH2 connection pool
This file contains 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
var ConnectionPool = function (connection) { | |
this.connection = connection; | |
this.queue = []; | |
this.counter = 0; | |
this.running = false; | |
}; | |
ConnectionPool.prototype.start = function () { | |
var self = this; | |
if (!this.running) { | |
this.running = true; | |
this.interval = setInterval(function () { | |
if(self.counter < 8) { | |
var saux = self.queue.shift(); | |
if (saux !== undefined) { | |
self.counter--; | |
self.connection.exec(saux.cmd, function (err, stream) { | |
if (err) { | |
self.counter++; | |
} else { | |
stream.on('data', function (data, extended) { | |
if (extended !== 'stderr' && saux.callback !== undefined) { | |
saux.callback(data); | |
} | |
}); | |
stream.on('exit', function (code, signal) { | |
stream.destroy(); | |
self.counter++; | |
}); | |
} | |
}); | |
} else { | |
self.stop(); | |
} | |
} | |
}, 50); | |
} | |
}; | |
ConnectionPool.prototype.flush = function () { | |
this.queue.length = 0; | |
}; | |
ConnectionPool.prototype.stop = function () { | |
this.running = false; | |
clearInterval(this.interval); | |
}; | |
ConnectionPool.prototype.send = function (cmd, callback) { | |
this.queue.push({'cmd': cmd, 'callback': callback}); | |
if (!this.running) { | |
this.start(); | |
} | |
}; | |
module.exports = ConnectionPool; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment