Deno 1.37.0中父子进程stdin流连接问题求解
Deno 1.37.0 父进程向子进程写入stdin无效的解决方案
你的问题出在父进程代码中没有实际向子进程的stdin写入数据,也未关闭stdin流,导致子进程的读取循环一直处于等待状态,无法输出内容。以下是修正后的完整代码:
修正后的 parent.ts
const command = new Deno.Command(Deno.execPath(), { args: ["run", "-A", "child.ts"], stdout: "piped", stdin: "piped" }); const p = command.spawn(); // 编码并写入数据到子进程stdin const encoder = new TextEncoder(); await p.stdin.write(encoder.encode("Hello from parent process!")); // 关闭stdin,告知子进程没有更多输入 p.stdin.close(); // 等待子进程执行完成并打印其输出 const output = await p.output(); console.log("Child process output:", new TextDecoder().decode(output.stdout));
child.ts 可保持不变
const decoder = new TextDecoder(); for await (const chunk of Deno.stdin.readable) { const text = decoder.decode(chunk); console.log(text); } Deno.stdin.close();
关键说明
- 父进程必须主动向子进程的
stdin写入数据,否则子进程的for await循环会一直监听输入,不会执行后续逻辑。 - 写入完成后务必调用
p.stdin.close(),否则子进程无法判断输入是否结束,会持续等待。 - 使用
TextEncoder将字符串转换为Deno标准输入支持的Uint8Array格式,读取时用TextDecoder转回字符串。
内容的提问来源于stack exchange,提问作者ferdiansyah0611
相关产品推荐
相关产品推荐

