Bun中如何实时获取异步spawn进程的输出
在Bun中实时读取spawn进程的输出
Bun的spawn API返回的stdout并非Node.js风格的EventEmitter,所以你熟悉的stdout.on('data')监听方式在这里不生效。要实现实时读取进程输出,得利用Bun本身的异步迭代器特性,以下是具体实现方案:
基础实现:实时读取stdout
Bun的stdout是实现了AsyncIterable接口的ReadableStream,你可以用for await...of循环来实时迭代输出内容:
import { spawn } from "bun"; const proc = spawn("some command"); // 实时捕获stdout输出 for await (const chunk of proc.stdout) { // 将Buffer转换为字符串,可指定编码如'utf-8' console.log(chunk.toString()); }
同时处理stdout和stderr
如果需要同时监听标准输出和错误输出,可以通过并行异步迭代实现:
import { spawn } from "bun"; const proc = spawn("some command"); async function handleProcessOutput() { // 并行处理两个流 await Promise.all([ (async () => { for await (const chunk of proc.stdout) { console.log("stdout:", chunk.toString()); } })(), (async () => { for await (const chunk of proc.stderr) { console.error("stderr:", chunk.toString()); } })() ]); } handleProcessOutput();
关键说明
Bun设计时没有兼容Node.js的stream事件API,而是采用了Web标准的ReadableStream + 异步迭代器模式,这是两者的核心差异。只要切换到异步迭代的方式,就能实现和Node.js中on('data')一样的实时输出效果。
内容的提问来源于stack exchange,提问作者Laurent
相关产品推荐
相关产品推荐

