對於 CLI 工具,通常從 stdin
讀取會很有用。在 Bun 中,console
物件是一個 AsyncIterable
,它會產生來自 stdin
的行。
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
程序的大型輸入很有用。
無法保證區塊會按行拆分。
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 > 工具 以取得更多有用的工具。