loading...

How to serialize that $%*#ing Buffer

subterrane profile image Will Munslow ・1 min read

I've been playing with TextEncoder and TextDecoder. Methods in the Web Crypto API work with a BufferSource which is fine but I need to encrypt some text, store it (actually send it, but it's stored), then decrypt it. For that, I needed to store and read the buffers. Encoding and decoding a buffer is simple, serializing and deserializing is simple AFTER you figure it out.

First, we need a buffer.

const buffer = new TextEncoder().encode('banana');

Not a problem. But now I want to put that in JSON (probably with a bunch of other properties) and read it back in later.

const testObj = {
    encodedText: buffer.toString()
};

const serializedTestObj = JSON.stringify(testObj);

If we log that out it looks pretty simple:

{"encodedText":"98,97,110,97,110,97"}

Getting an object is simple

const deserializedTestObj = JSON.parse(serializedTestObj);

But how do we get the encodedText back into a buffer? This is the part that seems really simple once you stop thinking so hard. Split the string on the commas into an array and use the from method of the TypedArray to get a Uint8Array.

const deserializedBuffer = deserializedTestObj.encodedText.split(',');
const newBuffer = Uint8Array.from(deserializedBuffer);

Then it's a simple decode to get our string back

const str = new TextDecoder().decode(newBuffer);
console.log(str); // banana

Posted on by:

Discussion

markdown guide