Advanced JavaScript objects serialization
1: If decoding target platform doesn't support encoded error type, it will fallback to Error
constructor.
2: If decoding target platform doesn't support Map
, it will be decoded as array of [key, value]
.
3: If decoding target platform doesn't support Set
, ArrayBuffer
or typed arrays, they will be decoded as array.
Install
npm install replicator
Usage
const Replicator = require('replicator');
const replicator = new Replicator();
const a = {};
a.b = a;
const str = replicator.encode({
key1: new Set([1, 2, 3]),
key2: /\s+/ig,
key3: a
});
const obj = replicator.decode(str);
Adding custom types support
You can extend replicator
with custom type transform which will describe how to serialize/deserialize objects. You can
add transforms using .addTransforms(transforms)
method. And remove them using .removeTransforms(transforms)
method.
Both methods are chainable and accept single transform or array of transforms. You should add transforms to both encoding
and decoding instances of replicator
.
Let's create transform which will encode NodeList
of elements and decode it as array of objects with tagName
property:
const Replicator = require('replicator');
const replicator = new Replicator();
replicator.addTransforms([
{
type: 'NodeList',
shouldTransform (type, val) {
return typeof NodeList === 'function' && val instanceof NodeList;
},
toSerializable (nodeList) {
return Array.prototype.slice.call(nodeList);
},
fromSerializable (val){
return val;
}
},
{
type: 'Element',
shouldTransform (type, val){
return typeof HTMLElement === 'function' && val instanceof HTMLElement;
},
toSerializable (element) {
return element.tagName;
},
fromSerializable (val) {
return { tagName: val };
}
}
]);
var str = replicator.encode(document.querySelectorAll('div'));
console.log(replicator.decode(str));
Built-in types support implemented using transforms, so you can take a look on replicator
source code for more examples.
Changing serialization format
By default replicator
uses JSON under the hood. But you can use any serializer by passing serializer adapter to Replicator
constructor. E.g., let's use BSON as serializer:
const Replicator = require('replicator');
const BSON = require('bson');
const replicator = new Replicator({
serialize (val) {
return BSON.serialize(val, false, true, false);
},
deserialize: BSON.deserialize
});
replicator.encode(['yo', 42]);
Author
Ivan Nikulin (ifaaan@gmail.com)