> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# console

> Bun 中的 console 对象

<Note>
  Bun 提供了一个兼容浏览器和 Node.js 的 [console](https://developer.mozilla.org/en-US/docs/Web/API/console)
  全局对象。本页仅记录 Bun 原生的 API。
</Note>

***

## 对象检查深度

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

* **命令行参数**：使用 `--console-depth <number>` 为单次运行设置深度
* **配置文件**：在 `bunfig.toml` 中设置 `console.depth` 以进行持久化配置
* **默认值**：对象默认被检查到 `2` 层深度

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
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` 中的行。

```ts adder.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
for await (const line of console) {
  console.log(line);
}
```

这对于实现交互式程序非常有用，比如下面的加法计算器示例。

```ts adder.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
console.log(`让我们加一些数字吧！`);
console.write(`计数：0\n> `);

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

运行该文件：

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun adder.ts
让我们加一些数字吧！
计数：0
> 5
计数：5
> 5
计数：10
> 5
计数：15
```
