Skip to main content
Bun 提供了一个兼容浏览器和 Node.js 的 console 全局对象。本页仅记录 Bun 原生的 API。

对象检查深度

Bun 允许你配置在 console.log() 输出中嵌套对象的显示深度:
  • 命令行参数:使用 --console-depth <number> 为单次运行设置深度
  • 配置文件:在 bunfig.toml 中设置 console.depth 以进行持久化配置
  • 默认值:对象默认被检查到 2 层深度
const nested = { a: { b: { c: { d: "deep" } } } };
console.log(nested);
// 默认(深度 2):{ a: { b: [Object] } }
// 设置深度为 4:{ a: { b: { c: { d: 'deep' } } } }
命令行参数优先于配置文件设置。

从标准输入读取

在 Bun 中,console 对象可以作为一个 AsyncIterable,用于顺序读取 process.stdin 中的行。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79adder.ts
for await (const line of console) {
  console.log(line);
}
这对于实现交互式程序非常有用,比如下面的加法计算器示例。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79adder.ts
console.log(`让我们加一些数字吧!`);
console.write(`计数:0\n> `);

let count = 0;
for await (const line of console) {
  count += Number(line);
  console.write(`计数:${count}\n> `);
}
运行该文件:
terminal
bun adder.ts
让我们加一些数字吧!
计数:0
> 5
计数:5
> 5
计数:10
> 5
计数:15