> ## 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.

# 从标准输入读取

在 Bun 中，`console` 对象是一个 `AsyncIterable`，它会从 `stdin` 中逐行产出内容。

```ts index.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const prompt = "输入一些内容：";
process.stdout.write(prompt);
for await (const line of console) {
  console.log(`你输入了：${line}`);
  process.stdout.write(prompt);
}
```

***

运行此文件会启动一个永不停歇的交互式提示，回显你输入的任何内容。

```sh terminal icon="terminal" theme={null}
bun run index.ts
```

```txt theme={null}
输入一些内容：hello
你输入了：hello
输入一些内容：hello again
你输入了：hello again
```

***

Bun 还将 `stdin` 暴露为 `BunFile`，即 `Bun.stdin`。用它来增量读取通过管道传入 `bun` 进程的大型输入。

不保证分块是按行分割的。

```ts stdin.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 chunk of Bun.stdin.stream()) {
  // chunk 是 Uint8Array
  // 这里将其转换为文本（假设是 ASCII 编码）
  const chunkText = Buffer.from(chunk).toString();
  console.log(`块：${chunkText}`);
}
```

***

运行 `stdin.ts` 会打印通过管道传入的任何内容。

```sh terminal icon="terminal" theme={null}
echo "hello" | bun run stdin.ts
```

```txt theme={null}
块：hello
```

***

参见 [工具](/runtime/utils) 了解更多实用工具。
