Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A utility object that caches inbound HTTP data, allow you to attach your event handlers after you make other asynchronous requests.
function StreamBuffer(req) {
var self = this
var buffer = []
var ended = false
var ondata = null
var onend = null
self.ondata = function(f) {
for(var i = 0; i < buffer.length; i++ ) {
f(buffer[i])
}
ondata = f
}
self.onend = function(f) {
onend = f
if( ended ) {
onend()
}
}
req.on('data', function(chunk) {
if( ondata ) {
ondata(chunk)
}
else {
buffer.push(chunk)
}
})
req.on('end', function() {
ended = true
if( onend ) {
onend()
}
})
req.streambuffer = self
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment