Languages
[Edit]
EN

JavaScript - encode text to base64 using stream

19 points
Created by:
Root-ssh
115270

In this short article, we would like to show how in JavaScriptencode 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 is sotred inside 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 ...'));

See also

  1. JavaScript - decode base64 to text using stream 
  2. JavaScript - Base64 encode and decode

  3. JavaScript - base64 with Unicode support

  4. JavaScript - convert string to Base64

  5. JavaScript - convert blob to base64

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join