> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/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/zh-CN/docs/Web/API/console) 全局对象。此页面仅记录 Bun 原生 API。
</Note>

***

## 对象检查深度

您可以配置 `console.log()` 打印嵌套对象的深度：

* **CLI 标志**：使用 `--console-depth <number>` 为单次运行设置深度
* **配置**：在 `bunfig.toml` 中设置 `console.depth` 以在多次运行中持久化
* **默认值**：对象默认检查到 `2` 层深度

```js theme={null}
const nested = { a: { b: { c: { d: "deep" } } } };
console.log(nested);
// 默认（深度 2）：{ a: { b: { c: [Object ...] } } }
// 深度 4：{ a: { b: { c: { d: 'deep' } } } }
```

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

***

## 从 stdin 读取

在 Bun 中，`console` 对象也是一个 `AsyncIterable`，可以逐行读取 `process.stdin`。

```ts adder.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
for await (const line of console) {
  console.log(line);
}
```

用于交互式程序，如下面的加法计算器。

```ts adder.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
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> `);
}
```

要运行该文件：

```bash terminal icon="terminal" theme={null}
bun adder.ts
Let's add some numbers!
Count: 0
> 5
Count: 5
> 5
Count: 10
> 5
Count: 15
```
