对于 CLI 工具,从 stdin 读取通常很有用。在 Bun 中,console 对象是一个 AsyncIterable,它从 stdin 生成行。
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 还通过 Bun.stdin 将 stdin 作为 BunFile 公开。这对于增量读取管道输入到 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 > 工具函数 获取更多有用的工具。