Skip to main content
On this page

@std/msgpack

概览 Jump to heading

此模块提供用于编码和解码 MessagePack 的函数。

MessagePack 是一种高效的二进制序列化格式,语言无关。它类似于 JSON,但通常生成的有效载荷更小。了解更多关于 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 支持对以下类型进行编码和解码:

  • number 数值类型
  • bigint 大整数
  • string 字符串
  • boolean 布尔值
  • null 空值
  • Uint8Array 无符号 8 位整型数组
  • 这些类型值的数组
  • 键为字符串或数字,值为这些类型的对象

添加到你的项目 Jump to heading

deno add jsr:@std/msgpack

查看 @std/msgpack 中的全部符号

什么是 MessagePack? Jump to heading

MessagePack 是一种紧凑、高速且无模式的二进制序列化格式。它设计上注重尺寸和速度的高效,适用于高性能应用以及不同编程语言之间的数据交换。

为什么使用 @std/msgpack? Jump to heading

  • MessagePack 非常适合在受信任服务之间传输紧凑、高速、无模式的数据。当你需要比 JSON 更高效的替代方案时,它非常有用。
  • 二进制安全:Uint8Array 可以在不增加 base64 开销的情况下完成往返转换。

示例 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);

自定义扩展类型

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

// 为 Date 使用 tag 1
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]));
      }
    },
  },
});

提示 Jump to heading

  • 注意 bigint 和 number 的区别:非常大的整数会被解码为 bigint 类型。
  • 为了与其他语言互操作,建议使用常见类型(number、string、boolean、null、数组、映射、字节数组)。

你找到了你需要的东西吗?

编辑此页面
隐私政策