运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

从 stdin 读取

在 Bun 中,console 对象是一个从 stdin 产生行的 AsyncIterable。

index.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
Text
Type something: hello
You typed: hello
Type something: hello again
You typed: hello again

Bun 还将 stdin 作为 BunFile(即 Bun.stdin)提供。使用它可以增量读取通过管道传入 bun 进程的大型输入。

数据块不保证按行拆分。

stdin.ts
for await (const chunk of Bun.stdin.stream()) {
  // chunk is Uint8Array
  // this converts it to text (assumes UTF-8 encoding)
  const chunkText = Buffer.from(chunk).toString();
  console.log(`Chunk: ${chunkText}`);
}

运行 stdin.ts 会输出通过管道传入的任何内容。

terminal
echo "hello" | bun run stdin.ts
Text
Chunk: hello

请参阅实用工具以了解更多实用工具。