對於 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 > 工具程式以了解更多有用的工具程式。