Advertisement
Guest User

step-counter.js

a guest
Jul 22nd, 2014
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var http = require('http');
  2. var url = require('url');
  3.  
  4. var step = 0;
  5. for (var i in process.argv) {
  6.    if (i < 2)
  7.      continue;
  8.    step = parseInt(process.argv[i]);
  9. }
  10.  
  11. var step_waits = [];
  12. function step_update( cont ) {
  13.     cont({'result': 'ok'});
  14.     var waits = step_waits;
  15.     step_waits = [];
  16.     for (var i in waits) {
  17.         waits[i].update();
  18.     }
  19. }
  20.  
  21. var actions = {
  22.     'step' : function( args, cont ) {
  23.         cont({'step': step});
  24.     },
  25.     'step:wait' : function( args, cont ) {
  26.         var step_old = args['step'];
  27.         if (step_old != undefined && step_old != step) {
  28.             cont({'step': step});
  29.         }
  30.         var waiter = {
  31.             'cont': cont,
  32.             'update': undefined
  33.         };
  34.         waiter.update = function() {
  35.             var cont = waiter.cont;
  36.             waiter.cont = undefined;
  37.             clearTimeout(waiter.timer);
  38.             if (cont == undefined) {
  39.                 return;
  40.             }
  41.             cont({'step': step});
  42.         }
  43.         waiter.timer = setTimeout(waiter.update, 4000);
  44.         step_waits.push(waiter);
  45.     },
  46.     'next' : function( args, cont ) {
  47.         //  console.log('next');
  48.         step++;
  49.         step_update(cont);
  50.     },
  51.     'prev' : function( args, cont ) {
  52.         // console.log('prev');
  53.         step--;
  54.         step_update(cont);
  55.     },
  56. };
  57.  
  58. http.createServer(function (req, res) {
  59.     var query = url.parse(req.url, true);
  60.     var path = query.pathname;
  61.     var args = query.query;
  62.     if (path != '/assist-control') {
  63.         res.writeHead(404, {'Content-Type': 'text/plain'});
  64.         res.end('nothing here');
  65.         return;
  66.     }
  67.     // console.log('action=' + args.action);
  68.     action = actions[args.action];
  69.     if (action == undefined) {
  70.         res.writeHead(404, {'Content-Type': 'text/plain'});
  71.         res.end('bad method');
  72.         return;
  73.     }
  74.     action(args, function(json) {
  75.         res.writeHead(200, {'Content-Type': 'application/json'});
  76.         res.end(JSON.stringify(json));
  77.     });
  78. }).listen(8081, '127.0.0.1');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement