My Union-based app seems to execute "after" before "before"

50 views
Skip to first unread message

Stuart Malin

unread,
Apr 30, 2012, 10:55:09 AM4/30/12
to flati...@googlegroups.com
I've been building a Union-based Web server, and it seems to me that the "after"  functions are executing *before* the "before" functions. I suspect I must be misunderstanding some set-up, or doing something wrong. Please help set me straight.

I've made a stripped down app that demonstrates this, and posted in StackOverflow:


TIA.

Charlie Robbins

unread,
Apr 30, 2012, 10:23:02 PM4/30/12
to flati...@googlegroups.com
Stuart,

This is actually expected behavior. A pipe chain is constructed by a union.RoutingStream instance from:

union.ResponseStream() --> after0 --> after1 --> after2 --> ... --> aftern --> http.Response() (see https://github.com/flatiron/union/blob/master/lib/routing-stream.js#L74-83)

So the `pipe` event on every Stream in the after chain is invoked immediately, but everyone of those Streams has an opportunity to modify the data sent to the response by implementing their own .pipe() method. 

So for example if your LoggingStream was

var stream   = new union.ResponseStream();
stream.once("data", function (req) {
  console.log({res: this.res.statusCode, method: this.req.method});
});
return stream;

You would see the console.log statements fire in the order you expect. It might be useful to read Max Ogden's recent blog post on Streams in node.js and how they work: http://maxogden.com/node-streams

Cheers,
Charlie

Stuart Malin

unread,
May 1, 2012, 9:45:27 AM5/1/12
to flati...@googlegroups.com
Charlie,

Thank you for the detailed answer. I changed my code to use a "data" event rather than a "pip" event and it functioned as you say (as I expected).

Please note that I took the code I had from the Union example for "after" (index.js), and as the name of the function implemented was "LoggerStream" I expected it to log the result. Perhaps you might include in that example some code that uses a "data" event (besides the "pipe" event) to help others who read the example and jump from it to a quick implementation without catching the subtle distinction of the named event that is used.

Thanks for the Flatiron family!

~Stuart~
Reply all
Reply to author
Forward
0 new messages