EN
JavaScript - decode base64 to text using stream
18
points
In this short article, we would like to show how in JavaScript, decode base64 to text using a simple stream logic.
Decoding in-stream is useful when we have a big amount of data that should be decoded (in some parts) reducing memory usage that is needed when atob()
is called with big base64 code as an argument.
Stream is useful when we transmit real-time produced data and we don't know the final length.
Practical example:
// ONLINE-RUNNER:browser;
function Base64DecoderStream() {
var self = this;
var storage = ''; // contains not decoded text yet
self.decode = function(base64) {
var input = storage + base64;
if (input.length > 2) {
var size = 4 * Math.floor(input.length / 4);
var data = input.substring(0, size);
var text = atob(data);
storage = input.substring(size);
return text;
}
return '';
};
self.reset = function() {
storage = '';
};
}
// ----------------------------------------------------------
// Usage example:
// Decoding with stream:
var stream = new Base64DecoderStream();
document.write(stream.decode('TWFuIGlzIGRpc3Rpbmd1a'));
document.write(stream.decode('XNoZWQsIG5vdCBvbmx5IG'));
document.write(stream.decode('J5IGhpcyByZWFzb24sIGJ'));
document.write(stream.decode('1dCAuLi4='));
document.write('<br />');
// Decoding with atob:
document.write(atob('TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCAuLi4'));