Bun

控制台

注意 — Bun 提供了一个与浏览器和 Node.js 兼容的 console 全局对象。此页面仅记录 Bun 原生的 API。

对象检查深度

Bun 允许您配置 console.log() 输出中显示嵌套对象的深度

  • CLI 标志:使用 --console-depth <number> 为单次运行设置深度
  • 配置:在您的 bunfig.toml 中设置 console.depth 以实现持久化配置
  • 默认:对象被检查的深度为 2
const nested = { a: { b: { c: { d: "deep" } } } };
console.log(nested);
// Default (depth 2): { a: { b: [Object] } }
// With depth 4: { a: { b: { c: { d: 'deep' } } } }

CLI 标志的优先级高于配置文件设置。

从 stdin 读取

在 Bun 中,console 对象可以用作 AsyncIterable,以顺序读取 process.stdin 的行。

for await (const line of console) {
  console.log(line);
}

这对于实现交互式程序很有用,例如下面的加法计算器。

adder.ts
console.log(`Let's add some numbers!`);
console.write(`Count: 0\n> `);

let count = 0;
for await (const line of console) {
  count += Number(line);
  console.write(`Count: ${count}\n> `);
}

运行文件

bun adder.ts
Let's add some numbers!
Count: 0
5
Count: 5
5
Count: 10
5
Count: 15