Skip to content

Files

Latest commit

f632bdf · Dec 11, 2023

History

History
88 lines (61 loc) · 1.86 KB

tpl.readme.md

File metadata and controls

88 lines (61 loc) · 1.86 KB

About

{{pkg.description}}

This implementation is a full rewrite & refactor of @ygoe/msgpack.js, based on this specification.

Supported values

  • numbers (i8/16/32, u8/16/32, bigint signed/unsigned 64bit range, floats)
  • strings (converted to UTF-8)
  • plain JS objects
  • arrays
  • typed arrays (as bytes)
  • Date objects
  • null

Custom types can be serialized via a user-provided resolve() function which is expected to produce a msgpack-compatible representation of the custom type(s).

As with JSON.stringify(), undefined values will be serialized as null and object keys with undefined will be entirely omitted in the serialization.

{{meta.status}}

{{repo.supportPackages}}

{{repo.relatedPackages}}

{{meta.blogPosts}}

Installation

{{pkg.install}}

{{pkg.size}}

Dependencies

{{pkg.deps}}

{{repo.examples}}

API

{{pkg.docs}}

import { deserialize, serialize } from "@thi.ng/msgpack";
import { equiv } from "@thi.ng/equiv";

const obj = {
	small_i8: -0x0f,
	i8: -0x80,
	small_u8: 0xff,
	i16: -0x8000,
	u16: 0xfedc,
	i32: -0x8000_0000,
	u32: 0xffff_ffff,
	utf8_array: ["👋 Hello", "msgpack!", "🔥🤌"],
	now: new Date()
};

// encode to byte array
const bytes = serialize(obj);
console.log(bytes);
// Uint8Array(114) [ 137, 168, 115, 109, 97, 108, 108, ... ]

// comparison with JSON
const json = JSON.stringify(obj);
const ratio = bytes.length / json.length;
console.log(`msgpack: ${bytes.length}, json: ${json.length}, ratio: ${ratio.toFixed(2)}`);
// msgpack: 114, json: 178, ratio: 0.64

// roundtrip
const obj2 = deserialize(bytes);

// check equality
console.log(equiv(obj, obj2));
// true