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:
numberbigintstringbooleannullUint8Array- 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
什么是 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、数组、映射、字节数组)。