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

# 从 stdin 读取

对于 CLI 工具来说，从 `stdin` 读取常常非常有用。在 Bun 中，`console` 对象是一个 `AsyncIterable`，它会产生来自 `stdin` 的行。

```ts index.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"}}
const prompt = "Type something: ";
process.stdout.write(prompt);
for await (const line of console) {
  console.log(`You typed: ${line}`);
  process.stdout.write(prompt);
}
```

***

运行此文件会得到一个永不结束的交互式提示，回显用户输入的内容。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run index.ts
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
Type something: hello
You typed: hello
Type something: hello again
You typed: hello again
```

***

Bun 还通过 `Bun.stdin` 将 stdin 作为一个 `BunFile` 暴露出来。这对于对通过管道传入 `bun` 进程的大量输入进行增量读取非常有用。

无法保证读取的块是逐行分割的。

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

***

这会打印通过管道传入 `bun` 进程的输入。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
echo "hello" | bun run stdin.ts
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
Chunk: hello
```

***

更多实用工具请参见 [文档 > API > Utils](/runtime/utils)。
