EN
JavaScript - encode text to base64 using stream
19
points
In this short article, we would like to show how in JavaScript, encode some text to base 64 using a simple stream logic.
Encoding in-stream is useful when we have a big amount of text that should be encoded (in some parts) reducing memory usage that is needed when btoa()
is called with big text as an argument.
Stream is useful when we transmit real-time produced text and we don't know the final length.
Practical example:
// ONLINE-RUNNER:browser;
function Base64EncoderStream() {
var self = this;
var storage = ''; // contains not encoded text yet
// Encodes text as base64, returning only part that can be encoded.
// Not encoded text part may sotred inside according to stream nature and can be extracted with finish() method.
//
self.encode = function(text) {
var input = storage + text;
if (input.length > 2) {
var size = 3 * Math.floor(input.length / 3);
var data = input.substring(0, size);
var code = btoa(data);
storage = input.substring(size);
return code;
}
return '';
};
// Extracts and encodes as base64 stored text part, resetting internal state.
//
self.finish = function() {
if (storage.length > 0) {
var code = btoa(storage);
storage = '';
return code;
}
return '';
};
self.reset = function() {
storage = '';
};
}
// ----------------------------------------------------------
// Usage example:
// Encoding with stream:
var stream = new Base64EncoderStream();
document.write(stream.encode('Man is distinguished, '));
document.write(stream.encode('not only by his reason, '));
document.write(stream.encode('but ...'));
document.write(stream.finish());
document.write('<br />');
// Encoding with btoa:
document.write(btoa('Man is distinguished, not only by his reason, but ...'));