antimony

drive firefox from node.js
git clone https://wehaveforgeathome.hates.computer/antimony.git
Log | Files | Refs | Submodules | LICENSE

client.js (1263B)


      1 var request = require('request');
      2 
      3 var Client = function (host) {
      4   this.host = host;
      5   this.out = 0;
      6   this.limit = 100;
      7   this.pending = [];
      8 };
      9 
     10 Client.prototype._runOnPage = function (url, f, callback) {
     11   var that = this;
     12   this.out++;
     13   var data = {
     14     type: 'page',
     15     url: url,
     16     script: f.toString()
     17   };
     18   var params = {
     19     uri: 'http://' + this.host + '/client',
     20     method: 'POST',
     21     body: JSON.stringify(data)
     22   };
     23   request(params, function (error, response, body) {
     24     if (error) { throw error; }
     25     var data = JSON.parse(body);
     26     callback(data.res);
     27     that.out--;
     28     that.handlePending();
     29   });
     30 };
     31 
     32 Client.prototype.handlePending = function () {
     33   var that = this;
     34   if (this.out >= this.limit) { return; }
     35   if (this.pending.length === 0) { return; }
     36   var remaining = this.limit - this.out;
     37   var j = (remaining <= this.pending.length) ? remaining : this.pending.length;
     38   for (var i = 0; i < j; i++) {
     39     var next = this.pending.shift();
     40     this._runOnPage(next.url, next.f, next.callback);
     41   }
     42 };
     43 
     44 Client.prototype.runOnPage = function (url, f, callback) {
     45   if (this.out < this.limit) {
     46     return this._runOnPage(url, f, callback);
     47   }
     48   this.pending.push({ url: url, f: f, callback: callback });
     49 };
     50 
     51 module.exports = Client;