1

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?

1 Answer 1

4

Buffer.alloc(doc) is not for what you want to achieve. The second argument of Buffer.alloc is to fill the buffer entirey with that value, repeting if neccesary. Is usually used to create a zero filled buffer, like so:

// 0 is the default value, so is not needed actually. Set for demo purposes.
let zerobuf = Buffer.alloc(1000, 0);

In this case, what you need is Buffer.from(doc):

let base64Text = Buffer.from(str).toString("base64");
let reconstitutedData = Buffer.from(base64Text, "base64").toString();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.