Skip to content

usernmae0101/array-buffer-serializer

Repository files navigation

array-buffer-serializer

CI codecov node-current

Similar (without fixed length data representation and some other minor differences) as CBOR or MessagePack, allows to encode an object into bytes before transmission via WebRTC or WebSocket and decode it back when received. This is very useful for network bandwidth when you need to send data to one or more recipients frequently. Works in both: browser and node.

Some characters of the Latin-1 Supplement are reserved for encoding values: C0 (U+00C0) - E3 (U+00E7). Supports only ASCII string.

Installation

Using npm:

npm install array-buffer-serializer

With yarn:

yarn add array-buffer-serializer

Usage

  1. Import Serializer object

    // as CommonJS
    const Serializer = require("array-buffer-serializer");
    // or ES6
    import Serializer from "array-buffer-serializer";
  2. Encode some data (object or array) using "toBuffer" method

    // as map
    const data = {this: "way"};
    // or array
    const data = ["or", "that", "way"];
    
    const buffer = Serializer.toBuffer(data);
  3. Send the buffer (for example, over WebScoket)

    ws.send(buffer);
  4. Receive the buffer and decode it using "fromBuffer" method

    ws.addEventListener("message", buffer => {
        const data = Serializer.fromBuffer(buffer);
    });

Compression

Type Data Bytes
Object (decoded) Raw (encoded) Decoded Encoded
undefined [undefined] <00 d4> 11 2
boolean [true] <00 d2> 6 2
[false] <00 d0> 7 2
null [null] <00 d6> 6 2
string ["text"] <00 dc 74 65 78 74 dc> 8 7
int8_t [255] <00 c0 ff> 5 3
int16_t [-65535] <00 c6 ff ff> 8 4
int32_t [4294967295] <00 c8 ff ff ff ff> 12 6
int53_t [9007199254740991] <00 cc ff ff ff ff ff ff 1f> 18 9
bigint [-18446744073709551615n] <00 e2 ff ff ff ff ff ff ff ff> 24 10
float [1.234567] <00 d8 3f 9e 06 4b> 10 6
double [1.23456789012] <00 da 3f f3 c0 ca 42 8c 1d 2b> 15 10

License

MIT