Skip to main content
On this page

@std/cbor

Unstable

This @std package is experimental and its API may change without a major version bump.

Overview Jump to heading

Overview

Concise Binary Object Representation (CBOR) is a binary data serialisation format optimised for compactness and efficiency. It is designed to encode a wide range of data types, including integers, strings, arrays, and maps, in a space-efficient manner. RFC 8949 - Concise Binary Object Representation (CBOR) spec.

Limitations

  • This implementation only supports the encoding and decoding of "Text String" keys.
  • This implementation encodes decimal numbers with 64 bits. It takes no effort to figure out if the decimal can be encoded with 32 or 16 bits.
  • When decoding, integers with a value below 2 ** 32 will be of type number, with all larger integers being of type bigint.

Functions and classes may have more specific limitations listed.

import { assert, assertEquals } from "@std/assert";
import { decodeCbor, encodeCbor } from "@std/cbor";

const rawMessage = "I am a raw Message!";

const encodedMessage = encodeCbor(rawMessage);
const decodedMessage = decodeCbor(encodedMessage);

assert(typeof decodedMessage === "string");
assertEquals(decodedMessage, rawMessage);

Add to your project Jump to heading

deno add jsr:@std/cbor

See all symbols in @std/cbor on

什么是 CBOR? Jump to heading

CBOR(简明二进制对象表示法)类似于 JSON 的二进制版本。它将数据存储为紧凑的二进制格式,而非文本,从而减少体积并加速解析。

它支持所有常见类型(数字、字符串、布尔值、null、数组、映射),还支持二进制数据和大整数。CBOR 通常用于网络传输数据(非常适合带宽有限的物联网或移动设备)、存储紧凑负载和语言之间的互操作性。

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

此包提供简单的函数,将 JavaScript 对象编码为 CBOR 二进制格式,并将 CBOR 二进制解码回 JavaScript 对象。

示例 Jump to heading

import { decodeCbor, encodeCbor } from "@std/cbor";

const obj = { t: "temp", v: 21.5, ts: Date.now() };
const bin = encodeCbor(obj);
const back = decodeCbor(bin);

二进制数据 (Uint8Array) Jump to heading

import { decodeCbor, encodeCbor } from "@std/cbor";

const bytes = new TextEncoder().encode("hello");
const encoded = encodeCbor(bytes);
const decoded = decodeCbor(encoded);

if (!(decoded instanceof Uint8Array)) throw new Error("expected bytes");
console.log(new TextDecoder().decode(decoded)); // "hello"

大整数行为 Jump to heading

大于 2**32 的整数解码为 bigint:

import { decodeCbor, encodeCbor } from "@std/cbor";

const bigNumber = 5_000_000_000; // > 2**32
const bigBytes = encodeCbor(bigNumber);
const bigValue = decodeCbor(bigBytes);

console.log(typeof bigValue); // "bigint"
console.log(bigValue === 5_000_000_000n); // true

const smallValue = decodeCbor(encodeCbor(42));
console.log(typeof smallValue); // "number"

序列(多个值) Jump to heading

import { decodeCborSequence, encodeCborSequence } from "@std/cbor";

const packet = encodeCborSequence([{ id: 1 }, { id: 2 }, "done" as const]);
const values = decodeCborSequence(packet);
// values: [{ id: 1 }, { id: 2 }, "done"]

标记值(日期) Jump to heading

使用 CBOR 标签 1 表示基于纪元的时间(自 Unix 纪元以来的秒数)。如何在解码时解释标签由你的应用决定。

import { decodeCbor, encodeCbor } from "@std/cbor";
import { CborTag } from "@std/cbor/tag";

const nowSeconds = Math.floor(Date.now() / 1000);
const tagged = new CborTag(1, nowSeconds);
const buf = encodeCbor(tagged);

const out = decodeCbor(buf) as CborTag;
console.log(out.tagNumber); // 1
console.log(out.tagContent); // 纪元秒数

解码守护模式 Jump to heading

处理不受信任的字节时,解码后检查数据结构。

import { decodeCbor } from "@std/cbor";

function isRecord(x: unknown): x is Record<string, unknown> {
  return typeof x === "object" && x !== null && !Array.isArray(x);
}

const bytesFromNetwork = new Uint8Array(/* ... */);
const value = decodeCbor(bytesFromNetwork);

if (!isRecord(value) || typeof value.type !== "string") {
  throw new Error("Unexpected payload");
}

// 使用安全
console.log(value.type);

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

编辑此页面
隐私政策