Bun

Console

注意 — Bun 提供了瀏覽器和 Node.js 相容的 console 全域物件。本頁面僅記錄 Bun 原生 API。

在 Bun 中,console 物件可以用作 AsyncIterable,以循序從 process.stdin 讀取行。

for await (const line of console) {
  console.log(line);
}

這對於實作互動式程式非常有用,例如以下加法計算器。

adder.ts
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