注意 — Bun 提供一個瀏覽器和 Node.js 相容的 主控台 全域變數。此頁面僅記載 Bun 原生的 API。
在 Bun 中,console
物件可用作 AsyncIterable
,以從 process.stdin
順序讀取行。
for await (const line of console) {
console.log(line);
}
這對於實作互動式程式很有用,例如以下的加法計算器。
console.log(`Let's add some numbers!`);
console.write(`Count: 0\n> `);
let count = 0;
for await (const line of console) {
count += Number(line);
console.write(`Count: ${count}\n> `);
}
執行檔案
bun adder.ts
Let's add some numbers!
Count: 0
5
Count: 5
5
Count: 10
5
Count: 15