I am trying to serialise and deserialise an object which contains multiple Buffers, however deserialising the resulting string from JSON.stringify() with JSON.parse() fails to correctly re-create the Buffers.
var b64 = 'Jw8mm8h+agVwgI/yN1egchSax0WLWXSEVP0umVvv5zM=';
var buf = new Buffer(b64, 'base64');
var source = {
a: {
buffer: buf
}
};
var stringify = JSON.stringify(source);
var parse = JSON.parse(stringify);
console.log("source: "+source.a.buffer.constructor.name);
console.log("parse: "+parse.a.buffer.constructor.name);
Gives the ouput:
source: Buffer
parse: Object
This makes sense since the output from Buffer.toJSON() creates a simple object like so:
{
type: "Buffer",
data: [...]
}
I guess I could traverse the resulting object looking for sub objects that have the above properties and convert them back to a Buffer, however I feel there should be a more elegant solution using JSON.parse() that I am missing.
You could use a reviver function that checks if an object looks like a stringified Buffer
, and create a proper instance from it:
var parse = JSON.parse(stringify, (k, v) => {
if (
v !== null &&
typeof v === 'object' &&
'type' in v &&
v.type === 'Buffer' &&
'data' in v &&
Array.isArray(v.data)) {
return new Buffer(v.data);
}
return v;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With