I favor creating small, reusable wrappers and getting into promise
code as quickly as possible.
https://gist.github.com/2126149
Kris Kowal
Heads up to any future passers-by: this approach unfortunately causes problems with anything other than a HEAD request, because every time you wait for a promise to resolve, you skip to the next tick of the event loop. But by then, you may have lost some of the response's data events.
Thus, using `promiseResponse` from Kris's gist, you cannot do:
promiseResponse(request).then(function (response) {
response.pipe(anotherStream);
}).end();
because pipe() will miss the data events between ticks.
data
and end
events
on the given obj
. Middleware performing async tasks should utilize this utility (or similar), to
re-emit data once the async operation has completed, otherwise these events may be lost. Ah, yeah. Node does not buffer input, just output. Such a pain.
Kris Kowal
It is definitely necessary to attache event listeners on a stream in
the first available turn.
I do happen to have a library for this. I use it in Q-FS and Q-HTTP.
It is predictably called Q-IO and it is not documented anywhere.
(Sorry!)
https://github.com/kriskowal/q-io/blob/master/q-io.js
In any case, this is how you would use it in this example:
https://gist.github.com/2345090
I’m assuming the existence of a client.get method here, since you are
particularly looking for something that provides the stream as the
eventual fulfillment.
Kris Kowal
Went down that route, somewhat.
Sadly until Node 0.9, stream.pause is advisory for HTTP [1], so you will lose data trying to do this. (Perhaps Connect's pause is different than Node's built-in, though.) Plus, from what I can gather pausing involves sending some kind of TCP message to the client, as does resuming, which is expensive.
Another workaround is a BufferedStream [2], which will hold things in memory for at least one tick. It feels like bad practice, though: I think I'm supposed to be streaming directly from server to server (e.g. Amazon S3 to my web server's client), not storing things in memory.
[1]: https://groups.google.com/forum/#!topic/nodejs/yv6Dl-O-wYk/discussion
[2]: https://github.com/mjijackson/bufferedstream/
From: q-con...@googlegroups.com [q-con...@googlegroups.com] on behalf of Christoph Dorn [christoph-gg@christophdorn.com]
Sent: Wednesday, April 04, 2012 15:20
To: q-con...@googlegroups.com
Subject: Re: [Q] Working with streams/requests/responses
Domenic Denicola
20 April, 2012 3:44 PM
It might be nicer to have a simple PromisedHttp(Client|Server)(Request|Response) class that is initialized by giving it a corresponding Http(Client|Server)(Request|Response). Hmm, maybe a fun project.