节点检测 child_process 等待从标准输入读取
Node detect child_process waiting to read from stdin
我发现了一些关于写入 child_process
标准输入的问题,例如 Nodejs Child Process: write to stdin from an already initialised process,但是,我想知道是否可以识别使用 Node 的 child_process
尝试从它的标准输入中读取并对此采取行动(可能根据它之前写入标准输出的内容)。
我看到 stdio 流是在 Node.js 中使用 Stream 实现的。 Stream 有一个名为 data
的事件,用于写入时,但是,我没有看到用于检测正在读取流的事件。
这里的方法是继承 Stream
并使用自定义实现覆盖其 read
方法还是有更简单的方法?
我已经尝试使用 Node 标准 I/O 和流,直到我最终找到解决方案。您可以在这里找到它:https://github.com/TomasHubelbauer/node-stdio
要点是我们需要创建一个 Readable
流并将其通过管道传输到进程的标准输入。然后我们需要监听进程的标准输出并解析它,检测感兴趣的块(提示给用户),每次我们得到其中一个,让我们的 Readable
输出我们对提示的“反应”到进程的标准输入。
启动进程:
const cp = child_process.exec('node test');
准备 Readable
并将其通过管道传输到进程的标准输入:
new stream.Readable({ read }).pipe(cp.stdin);
提供 read
进程要求输入时调用的实现:
/** @this {stream.Readable} */
async function read(/** @type {number} */ size) {
this.push(await promise + '\n');
}
此处 promise
用于阻塞,直到我们通过其标准输出得到进程提出的问题的答案。 this.push
会将答案添加到 Readable
的内部队列中,最终它会被发送到进程的标准输入。
如何解析程序提示的输入、从问题中得出答案、等待提供答案然后将其发送到进程的示例在链接的存储库中。
我发现了一些关于写入 child_process
标准输入的问题,例如 Nodejs Child Process: write to stdin from an already initialised process,但是,我想知道是否可以识别使用 Node 的 child_process
尝试从它的标准输入中读取并对此采取行动(可能根据它之前写入标准输出的内容)。
我看到 stdio 流是在 Node.js 中使用 Stream 实现的。 Stream 有一个名为 data
的事件,用于写入时,但是,我没有看到用于检测正在读取流的事件。
这里的方法是继承 Stream
并使用自定义实现覆盖其 read
方法还是有更简单的方法?
我已经尝试使用 Node 标准 I/O 和流,直到我最终找到解决方案。您可以在这里找到它:https://github.com/TomasHubelbauer/node-stdio
要点是我们需要创建一个 Readable
流并将其通过管道传输到进程的标准输入。然后我们需要监听进程的标准输出并解析它,检测感兴趣的块(提示给用户),每次我们得到其中一个,让我们的 Readable
输出我们对提示的“反应”到进程的标准输入。
启动进程:
const cp = child_process.exec('node test');
准备 Readable
并将其通过管道传输到进程的标准输入:
new stream.Readable({ read }).pipe(cp.stdin);
提供 read
进程要求输入时调用的实现:
/** @this {stream.Readable} */
async function read(/** @type {number} */ size) {
this.push(await promise + '\n');
}
此处 promise
用于阻塞,直到我们通过其标准输出得到进程提出的问题的答案。 this.push
会将答案添加到 Readable
的内部队列中,最终它会被发送到进程的标准输入。
如何解析程序提示的输入、从问题中得出答案、等待提供答案然后将其发送到进程的示例在链接的存储库中。