I'm trying to convert some base64 conversion code that used to use the insecure Buffer constructor to use the Buffer.alloc method instead, but the conversion is behaving strangely. Here is my code:
let originalText = JSON.stringify({city: "New York", date: "2020/05/12"});
console.log("DATA: " + originalText)
let base64Text = Buffer.alloc(originalText.length, originalText, "binary").toString('base64');
console.log("Base64 version: " + base64Text);
let loadedBuffer = Buffer.alloc(base64Text.length, base64Text, 'base64');
const reconstitutedData = loadedBuffer.toString();
console.log("Result: " + reconstitutedData);
And here is the output:
DATA: {"city":"New York","date":"2020/05/12"}
Base64 version: eyJjaXR5IjoiTmV3IFlvcmsiLCJkYXRlIjoiMjAyMC8wNS8xMiJ9
Result: {"city":"New York","date":"2020/05/12"}{"city":"New
The conversion is correct except for the repeated bit on the end. Obviously the length of the base64 string is not the right length to use here, but this makes no sense because it doesn't seem like there is a way to know the length of the original string. Maybe I'm using the API wrong?