Skip to content

Instantly share code, notes, and snippets.

@rjrodger
Created March 28, 2011 11:16
Show Gist options
  • Save rjrodger/890301 to your computer and use it in GitHub Desktop.
Save rjrodger/890301 to your computer and use it in GitHub Desktop.
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