Open in a new tab

Pack a small framed message (magic, version, length, payload, CRC-32) into bytes, parse it back, and show the bytes as a hex dump.

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

When to use it

You read or write a binary file or wire format: a fixed header, typed integers with a known endianness, a payload with a checksum. The same two modules handle typed arrays, strings and NUL-terminated strings.

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. Change MAGIC, VERSION and the field list in pack / unpack to your format.

What it shows

  • binaryWriter.create({ endian: 'be' }) with chainable ascii, u16, u32, bytes, then finalize() for the exact bytes.
  • binaryReader.create(bytes, { endian: 'be' }) reading the same fields in order; a wrong magic or a CRC mismatch throws instead of returning garbage.
  • crc32: new Crc32(), append(bytes), get() for an unsigned 32-bit checksum.
  • hex.fromBytes for the dump.

Code

main.js

javascriptApache-2.078 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { binaryReader } from '@awacloud/fw/io/binary/reader.js';
import { binaryWriter } from '@awacloud/fw/io/binary/writer.js';
import { hex } from '@awacloud/fw/io/codec/hex.js';
import { crc32 } from '@awacloud/fw/io/calc/crc32.js';

fw.runtime.registerAllDeep([binaryReader, binaryWriter, hex, crc32]);
const reader = fw.runtime.resolve('binaryReader');
const writer = fw.runtime.resolve('binaryWriter');
const HEX = fw.runtime.resolve('hex');
const Crc32 = fw.runtime.resolve('crc32');

const MAGIC = 'AWA1';
const VERSION = 2;

/** @param {Uint8Array} bytes */
export function checksum(bytes) {
    const crc = new Crc32();
    crc.append(bytes);
    return crc.get();
}

/**
 * magic (4 ASCII) · version u16 · length u32 · payload · crc32 u32, big-endian.
 * @param {string} text
 * @returns {Uint8Array}
 */
export function pack(text) {
    const payload = new TextEncoder().encode(text);
    return writer.create({ endian: 'be' })
        .ascii(MAGIC).u16(VERSION).u32(payload.length).bytes(payload).u32(checksum(payload))
        .finalize();
}

/**
 * @param {Uint8Array} bytes
 * @returns {{ version: number, length: number, crc: number, text: string }}
 * @throws {Error} on a wrong magic or a CRC mismatch
 */
export function unpack(bytes) {
    const r = reader.create(bytes, { endian: 'be' });
    if (r.ascii(4) !== MAGIC) throw new Error('not an AWA1 frame');
    const version = r.u16();
    const length = r.u32();
    const payload = r.bytes(length);
    const crc = r.u32();
    if (crc !== checksum(payload)) throw new Error('CRC-32 mismatch: payload corrupted');
    return { version, length, crc, text: new TextDecoder().decode(payload) };
}

/** 16 bytes per line, offset first. @param {Uint8Array} bytes */
export function hexDump(bytes) {
    const lines = [];
    for (let i = 0; i < bytes.length; i += 16) {
        const pairs = HEX.fromBytes(bytes.subarray(i, i + 16)).match(/../g) ?? [];
        const chunk = pairs.join(' ');
        lines.push(`${i.toString(16).padStart(8, '0')}  ${chunk}`);
    }
    return lines.join('\n');
}

const input = /** @type {HTMLTextAreaElement} */ (document.getElementById('payload'));
/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };

function update() {
    const bytes = pack(input.value);
    const frame = unpack(bytes);
    show('dump', hexDump(bytes));
    show('version', String(frame.version));
    show('length', `${frame.length} bytes`);
    show('crc', frame.crc.toString(16).padStart(8, '0'));
    show('text', frame.text);
}

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

index.html

htmlApache-2.031 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 · Write and read a binary header</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>Write and read a binary header</h1>
    <label for="payload">Payload</label>
    <textarea id="payload" rows="2">Hello, bytes!</textarea>
    <p>Layout: magic <code>AWA1</code> (4 ASCII bytes), version (u16), payload length (u32), payload, CRC-32 of the
      payload (u32), all big-endian.</p>
    <pre id="dump" aria-label="Hex dump"></pre>
    <dl>
      <dt>Version</dt><dd><output id="version"></output></dd>
      <dt>Payload length</dt><dd><output id="length"></output></dd>
      <dt>CRC-32</dt><dd><output id="crc"></output></dd>
      <dt>Payload read back</dt><dd><output id="text"></output></dd>
    </dl>
  </main>
</body>
</html>