Skip to main content
On this page

@std/msgpack

Overview Jump to heading

This module provides functions to encode and decode MessagePack.

MessagePack is an efficient binary serialization format that is language agnostic. It is like JSON, but generally produces much smaller payloads. Learn more about MessagePack.

import { decode, encode } from "@std/msgpack";
import { assertEquals } from "@std/assert";

const obj = {
  str: "deno",
  arr: [1, 2, 3],
  bool: true,
  nil: null,
  map: {
    foo: "bar"
  }
};

const encoded = encode(obj);
assertEquals(encoded.length, 42);

const decoded = decode(encoded);
assertEquals(decoded, obj);

MessagePack supports encoding and decoding the following types:

  • number
  • bigint
  • string
  • boolean
  • null
  • Uint8Array
  • arrays of values of these types
  • objects with string or number keys, and values of these types

Add to your project Jump to heading

deno add jsr:@std/msgpack

See all symbols in @std/msgpack on

What is MessagePack? Jump to heading

MessagePack is a binary serialization format that is compact, fast, and schema-less. It is designed to be efficient in both size and speed, making it suitable for high-performance applications and data exchange between different programming languages.

Why use @std/msgpack? Jump to heading

  • MessagePack is great for compact, fast, schema-less payloads between trusted services. Useful if you need a more efficient alternative to JSON.
  • Binary-safe: Uint8Array round-trips without base64 overhead.

Examples Jump to heading

import { decode, encode } from "@std/msgpack";

const payload = { id: 1, items: ["a", "b"], data: new Uint8Array([1, 2, 3]) };
const bin = encode(payload);
const back = decode(bin);

Custom extension types

import { Decoder, Encoder, ExtData } from "@std/msgpack";

// tag 1 for Date
const enc = new Encoder({
  extensionCodec: {
    tryToEncode(object) {
      if (object instanceof Date) {
        return new ExtData(
          1,
          new Uint8Array(new BigInt64Array([BigInt(object.getTime())]).buffer),
        );
      }
    },
  },
});

const dec = new Decoder({
  extensionCodec: {
    decode(data) {
      if (data.type === 1) {
        return new Date(Number(new BigInt64Array(data.data.buffer)[0]));
      }
    },
  },
});

Tips Jump to heading

  • Beware of bigint vs number: very large integers decode to bigint.
  • For interop with other languages, stick to common types (number, string, boolean, null, arrays, maps, bytes).

Did you find what you needed?

Privacy policy