Created
February 5, 2012 22:29
-
-
Save max-mapper/1748217 to your computer and use it in GitHub Desktop.
node bufferedstream proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = require('request'); | |
var BufferedStream = require('morestreams').BufferedStream; | |
function requestHandler(req, res) { | |
// immediately pipe the incoming request into a paused bufferedstream. | |
// if you try to pipe after a nextTick it won't work because data starts | |
// arriving immediately | |
var bufferedStream = new BufferedStream | |
bufferedStream.pause() | |
req.pipe(bufferedStream) | |
before(req, res, function(err) { | |
// after the async stuff finishes then you can connect proxy | |
createProxy(req, res, bufferedStream) | |
}) | |
} | |
// example function that might do some async stuff (e.g. validation, logging). | |
// you only need bufferedstream if you have to do async stuff between when a | |
// request comes in and when you want to .pipe() that request somewhere | |
function before(req, res, callback) { | |
process.nextTick(function() { | |
callback() | |
}) | |
} | |
function createProxy(req, resp, bufferedStream) { | |
// req.pipe() copies the incoming http request properties onto the new | |
// request instance | |
var proxy = request() | |
req.pipe(proxy) | |
bufferedStream.pipe(proxy) | |
proxy.pipe(resp) | |
bufferedStream.resume() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
also piping twice to the same response will result in you getting a warning that says
You have already piped to this stream. Pipeing twice is likely to break the request
but @mikeal is gonna fixrequest
so that there is a method exposed that will let you clone the settings of an http request without having to use .pipe()