Skip to content

對於 CLI 工具,從 stdin 讀取通常很有用。在 Bun 中,console 對象是一個 AsyncIterable,它從 stdin 生成行。

ts
const prompt = "輸入一些內容:";
process.stdout.write(prompt);
for await (const line of console) {
  console.log(`你輸入了:${line}`);
  process.stdout.write(prompt);
}

運行此文件會產生一個永不結束的交互式提示,回顯用戶輸入的任何內容。

sh
bun run index.ts
txt
輸入一些內容:hello
你輸入了:hello
輸入一些內容:hello again
你輸入了:hello again

Bun 還通過 Bun.stdin 將 stdin 作為 BunFile 公開。這對於增量讀取管道輸入到 bun 進程的大型輸入很有用。

無法保證塊會按行分割。

ts
for await (const chunk of Bun.stdin.stream()) {
  // chunk 是 Uint8Array
  // 這將其轉換為文本(假設 ASCII 編碼)
  const chunkText = Buffer.from(chunk).toString();
  console.log(`塊:${chunkText}`);
}

這將打印管道輸入到 bun 進程的輸入。

sh
echo "hello" | bun run stdin.ts
txt
塊:hello

請參閱 文檔 > API > 工具函數 獲取更多有用的工具。

Bun學習網由www.bunjs.com.cn整理維護