what is a Base64 string? code example
Example 1: buffer from base64
const b64string = ;
const buf = Buffer.from(b64string, 'base64');
Example 2: working with binary and base64 data
Base64.byteToCharMap_ = null;
Base64.charToByteMap_ = null;
Base64.byteToCharMapWebSafe_ = null;
Base64.charToByteMapWebSafe_ = null;
Base64.ENCODED_VALS_BASE =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789';
Base64.ENCODED_VALS = Base64.ENCODED_VALS_BASE + '+/=';
Base64.ENCODED_VALS_WEBSAFE = Base64.ENCODED_VALS_BASE + '-_.';
Base64.encodeByteArray = function(input, opt_webSafe) {
Base64.init_();
var byteToCharMap = opt_webSafe ?
Base64.byteToCharMapWebSafe_ :
Base64.byteToCharMap_;
var output = [];
for (var i = 0; i < input.length; i += 3) {
var byte1 = input[i];
var haveByte2 = i + 1 < input.length;
var byte2 = haveByte2 ? input[i + 1] : 0;
var haveByte3 = i + 2 < input.length;
var byte3 = haveByte3 ? input[i + 2] : 0;
var outByte1 = byte1 >> 2;
var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
var outByte3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6);
var outByte4 = byte3 & 0x3F;
if (!haveByte3) {
outByte4 = 64;
if (!haveByte2) {
outByte3 = 64;
}
}
output.push(byteToCharMap[outByte1],
byteToCharMap[outByte2],
byteToCharMap[outByte3],
byteToCharMap[outByte4]);
}
return output.join('');
};
Base64.init_ = function() {
if (!Base64.byteToCharMap_) {
Base64.byteToCharMap_ = {};
Base64.charToByteMap_ = {};
Base64.byteToCharMapWebSafe_ = {};
Base64.charToByteMapWebSafe_ = {};
for (var i = 0; i < Base64.ENCODED_VALS.length; i++) {
Base64.byteToCharMap_[i] =
Base64.ENCODED_VALS.charAt(i);
Base64.charToByteMap_[Base64.byteToCharMap_[i]] = i;
Base64.byteToCharMapWebSafe_[i] =
Base64.ENCODED_VALS_WEBSAFE.charAt(i);
Base64.charToByteMapWebSafe_[
Base64.byteToCharMapWebSafe_[i]] = i;
}
}
};