從 stdin 讀取
在 Bun 中,console 物件是一個從 stdin 產生行的 AsyncIterable。
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 行程的大型輸入。
資料塊不保證按行拆分。
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
請參閱實用工具以瞭解更多實用工具。