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 > 工具