javascript - Function pipeline in Node JS web server -


i'm working on function pipeline similar connect/express request pipeline use()..

a request handler runs through stack of functions added using .use() function. async, n() function must called continue.

the functions called using familiar (req, res, next). works, last added first executed, i'm finding confusing , i'd make first added first executed. works last in , continues r, s references across pipeline..

(i use r, s instead of req, res in these examples..)

var s = {     chain: function(r, s, n){         // runs last, first added         s.end();     },     use: function (f){         this.chain = (function(nxt){             return function(r, s, n){                 f(r, s, nxt.bind(this, r, s));             }         })(this.chain);     },     listen: function (){         this.use(function (r, s, n){             // runs first, last added                 n();         })         var svr = require('http').createserver(this.chain);         svr.listen.apply(svr, [].slice.call(arguments));  // accept same args     } } s.use(function(r,s,n){...}); s.use(function(r,s,n){...}); s.listen(8080); 

here's attempt @ fifo. doesn't work. ideas?

var chain = function(r, s, n){     console.log(1, arguments);     n(); };  function use(f){     var th = chain;     chain = (function(nxt){         return function(r, s){             th(r, s, nxt);         }     })(f); }  use(function(r, s, n){     console.log(2, arguments)     n(); })  use(function(r, s, n){     console.log(3, arguments)     n(); })  chain(0,1); 

would doesn't use loops run thru functions.

i don't you're trying duplicate, this fiddle serve starting point?

var chain = function(fn) {     var queue = fn ? [fn] : [], index = 0, req, res;     var run = function(r, s) {         req = req || r; res = res || s;         if (index < queue.length) {             queue[index++](req, res, run);         }         };      return {         use: function(fn) {             queue.push(fn);             },         run: run     }; };  var c = chain(); c.use(function(r, s, n) {log(r, s, 1); n();}); c.use(function(r, s, n) {log(r, s, 2); n();}); c.use(function(r, s, n) {log(r, s, 3); n();}); c.use(function(r, s, n) {log(r, s, 4); n();});  c.run("req", "res");  //=> req, res, 1 //   req, res, 2 //   req, res, 3 //   req, res, 4 

you supply function in initial call chain if preferred.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -