Skip to main content
对于 CLI 工具来说,从 stdin 读取常常非常有用。在 Bun 中,console 对象是一个 AsyncIterable,它会产生来自 stdin 的行。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79index.ts
const prompt = "Type something: ";
process.stdout.write(prompt);
for await (const line of console) {
  console.log(`You typed: ${line}`);
  process.stdout.write(prompt);
}

运行此文件会得到一个永不结束的交互式提示,回显用户输入的内容。
terminal
bun run index.ts
Type something: hello
You typed: hello
Type something: hello again
You typed: hello again

Bun 还通过 Bun.stdin 将 stdin 作为一个 BunFile 暴露出来。这对于对通过管道传入 bun 进程的大量输入进行增量读取非常有用。 无法保证读取的块是逐行分割的。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79stdin.ts
for await (const chunk of Bun.stdin.stream()) {
  // chunk 是 Uint8Array
  // 将其转换为文本(假设 ASCII 编码)
  const chunkText = Buffer.from(chunk).toString();
  console.log(`Chunk: ${chunkText}`);
}

这会打印通过管道传入 bun 进程的输入。
terminal
echo "hello" | bun run stdin.ts
Chunk: hello

更多实用工具请参见 文档 > API > Utils