Skip to main content
On this page

@std/yaml

概述 Jump to heading

parsestringify 用于处理YAML 编码的数据。

移植自 js-yaml v3.13.1

使用 parseAll 来解析一个 YAML 字符串中的多个文档。

该包通常支持 YAML 1.2.x(最新版本)以及一些在实际中常用的YAML 1.1特性。

支持的 YAML 1.1 特性包括:

  • 合并 类型(<< 符号)

不支持的 YAML 1.1 特性包括:

  • 布尔类型的 Yes、No、On、Off 字面量
  • 六十进制数字(例如 3:25:45
import { parse, stringify } from "@std/yaml";
import { assertEquals } from "@std/assert";

const data = parse(`
foo: bar
baz:
  - qux
  - quux
`);
assertEquals(data, { foo: "bar", baz: ["qux", "quux"] });

const yaml = stringify({ foo: "bar", baz: ["qux", "quux"] });
assertEquals(
  yaml,
  `foo: bar
baz:
  - qux
  - quux
`,
);

限制

  • binary 类型当前尚不稳定。

添加到你的项目 Jump to heading

deno add jsr:@std/yaml

查看 @std/yaml 中的所有符号

什么是 YAML? Jump to heading

YAML(YAML 不是标记语言)是一种易于人类阅读的数据序列化格式, 通常用于配置文件和不同语言之间的数据交换。 它强调简单性和可读性,使人类易于编写和理解。

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

YAML 非常适合优先考虑人类可读性的配置文件和数据交换场景。 当你需要以一种便于人类阅读和编辑的方式表示复杂数据结构时,使用它。 该模块提供了简单的函数来解析和序列化 YAML 数据。

示例 Jump to heading

读取配置文件(带错误处理) Jump to heading

import { parse } from "@std/yaml";

const raw = await Deno.readTextFile("config.yaml");
let config;
try {
  config = parse(raw);
} catch (err) {
  if (err instanceof SyntaxError) {
    console.error("无效的 YAML:", err.message);
  }
  throw err;
}

// 在使用前根据需要进行类型缩小/校验
if (
  typeof config === "object" && config !== null &&
  "port" in config && typeof config.port === "number"
) {
  console.log("监听端口", config.port);
}

一个文件中的多个文档 Jump to heading

import { parseAll } from "@std/yaml";

const docs = parseAll(`
---
name: dev
port: 3000
---
name: prod
port: 80
`);

// 例如,将环境名映射到端口号
const envToPort = Object.fromEntries(docs.map((d) => [d.name, d.port]));
console.log(envToPort.dev, envToPort.prod);

生成稳定的 YAML 差异(排序键,换行) Jump to heading

import { stringify } from "@std/yaml";

const data = {
  name: "service",
  description: "演示长行如何换行的示例。",
  tags: ["alpha", "beta", "gamma"],
  nested: { z: 1, a: 2, m: 3 },
};

const yaml = stringify(data, { sortKeys: true, lineWidth: 60, indent: 2 });
console.log(yaml);

YAML 锚点与合并键(YAML 1.1) Jump to heading

import { parse } from "@std/yaml";

const cfg = parse(`
defaults: &base
  retries: 3
  timeout: 5s

serviceA:
  <<: *base
  timeout: 10s

serviceB:
  <<: *base
`);

console.log(cfg.serviceA.timeout); // "10s"
console.log(cfg.serviceB.retries); // 3

序列化时跳过不支持的值 Jump to heading

import { stringify } from "@std/yaml";

const obj = { ok: 1, skipMe: () => {} };
// 默认情况下,函数会导致 TypeError。使用 skipInvalid 选项可以忽略它们。
const yaml = stringify(obj, { skipInvalid: true });
console.log(yaml);

将 YAML 写回磁盘 Jump to heading

import { stringify } from "@std/yaml";

const settings = { port: 8080, features: { a: true, b: false } };
await Deno.writeTextFile("settings.yaml", stringify(settings, { indent: 2 }));

使用技巧 Jump to heading

  • 如果预期一个字符串中有多个 YAML 文档,请使用 parseAll
  • 推荐在机器间互换使用 JSON;YAML 非常适合手工编辑的配置文件。
  • 为了在版本控制系统中获得稳定的差异,使用 stringify 时请设置 sortKeys: true 并固定 indentlineWidth

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

编辑此页面
隐私政策