Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner

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