CLI ツールでは、stdin から読み取ることが役立つ場合があります。Bun では、console オブジェクトは stdin から行を生成する AsyncIterable です。
ts
const prompt = "何か入力してください:";
process.stdout.write(prompt);
for await (const line of console) {
console.log(`入力された内容:${line}`);
process.stdout.write(prompt);
}このファイルを実行すると、ユーザーが入力したものをエコーする無限のインタラクティブプロンプトになります。
sh
bun run index.tstxt
何か入力してください:hello
入力された内容:hello
何か入力してください:hello again
入力された内容:hello againBun は stdin を BunFile として Bun.stdin を通じて公開します。これは bun プロセスにパイプされる大きな入力を段階的に読み取るのに役立ちます。
チャンクが行単位で分割されるという保証はありません。
ts
for await (const chunk of Bun.stdin.stream()) {
// chunk は Uint8Array
// これをテキストに変換(ASCII エンコードを想定)
const chunkText = Buffer.from(chunk).toString();
console.log(`チャンク:${chunkText}`);
}これにより、bun プロセスにパイプされた入力が出力されます。
sh
echo "hello" | bun run stdin.tstxt
チャンク:helloさらに便利なユーティリティについては、ドキュメント > API > ユーティリティ を参照してください。