Skip to content

Instantly share code, notes, and snippets.

@andris9
Created September 12, 2010 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andris9/576480 to your computer and use it in GitHub Desktop.
Save andris9/576480 to your computer and use it in GitHub Desktop.
var EventEmitter = require('events').EventEmitter,
sys = require('sys');
this.Base64Stream = function(){
EventEmitter.call(this);
this.current = "";
}
sys.inherits(this.Base64Stream, EventEmitter);
this.Base64Stream.prototype.push = function(data){
var remainder = 0;
this.current += data.replace(/[^\w+\/=]/g,'');
this.emit("stream", new Buffer(this.current.substr(0, this.current.length - this.current.length % 4),"base64"));
this.current = (remainder=this.current.length % 4)?this.current.substr(- remainder):"";
}
this.Base64Stream.prototype.end = function(){
this.emit("end");
}
// TEST:
var b64streamer = new this.Base64Stream();
// client, listens for the stream
b64streamer.on("stream",function(buffer){
// buffer: buffer containing the bytestream
console.log(buffer.toString("utf-8"))
});
b64streamer.on("end",function(){
console.log("stream completed")
});
// server, sends some test data
var test_data = "U2FpbiB0w6RuYSBUVMOcIGtpcmphc3R1c2VzdCBrw6R0dGUgYWpha2lyamEgQSZBIHV1ZSBudW1i\r\n"+
"cmkgKDIvMjAxMCksIGt1cyBvbiBzZWVzIG1pbnUgYXJ0aWtrZWwgR29vZ2xlIEFwcCBFbmdpbmUg\r\n"+
"a2FzdXRhbWlzZXN0IChrYWhqdWtzIHBvbGUgc2VkYSBvbmxpbmUga3Vza2lsdCB2aWlkYXRhKS4g\r\n"+
"S2lpcmVsdCBvdHNpZGVzIGxlaWRzaW4gdGVydmUgcml2aSBiYWthbGF1cmV1c2V0w7ZpZCBqYSB2\r\n"+
"w6RoZW1hbHQgw7xoZSBtYWdpc3RyaXTDtsO2LCBtaXMgYWxsaWthbmEgdmlpdGF2YWQgbcO1bmVs\r\n"+
"ZSBBJkEgYXJ0aWtsaWxlLCBzZWVnYSBvbiB0ZWd1IHTDpGllc3RpIHJlc3Bla3RhYWJsaSBhdmFs\r\n"+
"ZGFtaXNrb2hhZ2EgOikNCg0KQWludXMgcHJvbGJlZW0gYW50dWQgYWpha2lyamEganV1cmVzIG9u\r\n"+
"LCBldCBzZWRhIG9uIHByYWt0aWxpc2VsdCB2w7VpbWF0dSBrdXNraWx0IG9zdGEuIE1pbmEgbsOk\r\n"+
"aXRla3MgcG9sZSBzZWRhIGt1c2tpbCBtw7zDvGdpbCBuw6RpbnVkLiBBdXNhbHQgw7ZlbGRlcywg\r\n"+
"bWEgZWkgdGVhZG51ZGtpIHNlbGxlc3QgYWpha2lyamFzdCBzdXVydCBtaWRhZ2kgZW5uZSBrdWkg\r\n"+
"bXVsbGUgcGFrdXRpIHbDtWltYWx1c3Qgc2lubmEgb21hIGFydGlra2VsIGtpcmp1dGFkYS4gS3V1\r\n"+
"bG51ZCBvbGluLCBhZ2EgbsOkaW51ZCBtaXR0ZS4=\r\n",
cur_pos = 0, step = 27;
while(cur_pos < test_data.length){
b64streamer.push(test_data.substr(cur_pos, step))
cur_pos+=step;
}
b64streamer.end();
@andris9
Copy link
Author

andris9 commented Sep 12, 2010

Base64Stream makes it possible to parse asynchronously base64 encoded data in large quantities - for example binary e-mail attachments in MIME formatted messages. Instead of reading the whole data into memory, it can be processed in smaller chunks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment