Skip to main content
对于 CLI 工具来说,经常需要从 stdin 读取数据。在 Bun 中,console 对象是一个 AsyncIterable,它会产生来自 stdin 的行。
https://mintcdn.com/teemo/2s-4Z6VdGqiCeBNX/icons/typescript.svg?fit=max&auto=format&n=2s-4Z6VdGqiCeBNX&q=85&s=087b260066909db1cd3e9c7292bc34b2index.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/teemo/2s-4Z6VdGqiCeBNX/icons/typescript.svg?fit=max&auto=format&n=2s-4Z6VdGqiCeBNX&q=85&s=087b260066909db1cd3e9c7292bc34b2stdin.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 > 工具 了解更多的实用工具。