Bun

指南进程

使用 Bun 从 stdin 读取

对于 CLI 工具,通常需要从 stdin 读取。在 Bun 中,console 对象是一个 AsyncIterable,它会产生 stdin 的行。

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);
}

运行此文件将导致一个永无止境的交互式提示,它会回显用户输入的任何内容。

bun run index.ts
Type something: hello
You typed: hello
Type something: hello again
You typed: hello again

Bun 还通过 Bun.stdin 将 stdin 暴露为一个 BunFile。这对于逐步读取输入到 bun 进程的大型输入很有用。

不保证块会逐行拆分。

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

这将打印输入到 bun 进程的内容。

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

有关更多有用的工具,请参阅 文档 > API > 工具