Open in a new tab

Encode one flat record as CBOR, MessagePack, CSV and XML, compare the sizes with JSON, and decode each encoding back to an equal record.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

You exchange structured data with a service, a file format or another tab and want to pick an encoding on facts: binary and compact (CBOR, MessagePack), tabular text (CSV) or markup that other tools already read (XML).

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Keep the codecs you need; each import line is one module.

What it shows

  • cbor.encode / decode and msgpack.encode / decode: typed binary round trips, smaller than JSON for the same record.
  • csv.stringify([record]) and csv.parse(text, { header: true, cast: true }): the header row carries the keys, cast restores numbers and booleans.
  • xml.el / xml.text / xml.serializeNode to build markup, xml.parse / findChild / textContent to read it back. XML has no types, so the example restores them by hand, which is the honest shape.
  • Corrupted bytes throw instead of returning a partial record.

Code

main.js

javascriptApache-2.080 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { cbor } from '@awacloud/fw/io/codec/cbor.js';
import { msgpack } from '@awacloud/fw/io/codec/msgpack.js';
import { csv } from '@awacloud/fw/io/codec/csv.js';
import { xml } from '@awacloud/fw/io/codec/xml.js';

fw.runtime.registerAllDeep([cbor, msgpack, csv, xml]);
const CBOR = fw.runtime.resolve('cbor');
const MSGPACK = fw.runtime.resolve('msgpack');
const CSV = fw.runtime.resolve('csv');
const XML = fw.runtime.resolve('xml');
const encoder = new TextEncoder();
const decoder = new TextDecoder();

/** @typedef {{ id: number, name: string, role: string, score: number, active: boolean }} Person */
/** @type {Person} */
export const RECORD = { id: 42, name: 'Ada Lovelace', role: 'engineer', score: 9.5, active: true };

/**
 * The same flat record in four encodings (all as bytes so sizes compare).
 * @param {Person} record
 * @returns {Record<string, Uint8Array>}
 */
export function encodeAll(record) {
    const attrs = { id: String(record.id), score: String(record.score), active: String(record.active) };
    const doc = XML.el('record', attrs, [
        XML.el('name', {}, [XML.text(record.name)]),
        XML.el('role', {}, [XML.text(record.role)]),
    ]);
    return {
        JSON: encoder.encode(JSON.stringify(record)),
        CBOR: CBOR.encode(record),
        MessagePack: MSGPACK.encode(record),
        CSV: encoder.encode(CSV.stringify([record])),
        XML: encoder.encode(XML.serializeNode(doc)),
    };
}

/**
 * Decode each back; CSV (`cast`) and XML (by hand) restore numbers and booleans from text.
 * @param {Record<string, Uint8Array>} encoded @returns {Record<string, Person>} */
export function decodeAll(encoded) {
    const root = XML.parse(decoder.decode(encoded.XML));
    const child = (/** @type {string} */ name) => XML.textContent(XML.findChild(root, name));
    const { id, score, active } = root.attrs;
    return {
        JSON: JSON.parse(decoder.decode(encoded.JSON)),
        CBOR: CBOR.decode(encoded.CBOR),
        MessagePack: MSGPACK.decode(encoded.MessagePack),
        CSV: CSV.parse(decoder.decode(encoded.CSV), { header: true, cast: true })[0],
        XML: { id: Number(id), name: child('name'), role: child('role'),
            score: Number(score), active: active === 'true' },
    };
}

/** @param {Person} a @param {Person} b */
export const sameRecord = (a, b) => JSON.stringify(a) === JSON.stringify(b);

const input = /** @type {HTMLInputElement} */ (document.getElementById('name'));
const rows = /** @type {HTMLElement} */ (document.getElementById('rows'));
const sample = /** @type {HTMLElement} */ (document.getElementById('xml'));

function update() {
    const record = { ...RECORD, name: input.value };
    const encoded = encodeAll(record);
    const decoded = decodeAll(encoded);
    rows.replaceChildren(...Object.keys(encoded).map((name) => {
        const row = document.createElement('tr');
        const verdict = sameRecord(decoded[name], record) ? 'equal' : 'DIFFERENT';
        for (const cell of [name, String(encoded[name].length), verdict]) {
            row.appendChild(document.createElement('td')).textContent = cell;
        }
        return row;
    }));
    sample.textContent = decoder.decode(encoded.XML);
}

input.addEventListener('input', update);
update();

index.html

htmlApache-2.028 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · One record, four encodings</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>One record, four encodings</h1>
    <label for="name">Name</label>
    <input id="name" type="text" value="Ada Lovelace" autocomplete="off">
    <table>
      <caption>Size of the encoded record, and whether decoding it gives the record back</caption>
      <thead><tr><th scope="col">Encoding</th><th scope="col">Bytes</th><th scope="col">Round trip</th></tr></thead>
      <tbody id="rows"></tbody>
    </table>
    <p>XML sample: <code id="xml"></code></p>
  </main>
</body>
</html>