Node.JS:在收到标准输出数据后写入子进程生成

问题描述

要做什么:我已经用c ++编写了一个象棋引擎,并将其编译为可执行文件。我现在正在使用Node.JS来使该引擎与国际象棋网站的API通信(以便人类和其他引擎可以挑战它)。

我正在使用Node.JS的child_process模块创建一个spawn,它将促进API与引擎之间的I / O通信。

为了告诉引擎新游戏已经开始,我在过程中写了"UCI\n"。然后,我等待引擎输出"id name {engine name}\r\nid author {my name}\r\nuciok\r\n"。从引擎收到此输出后,我需要将"isready\n"写回它,以便以后可以开始生成移动。

我的问题:我面临的问题是,在我最初"UCI\n"对该过程进行写操作之后,我打电话给child_process.spawn().stdin.end()。看来此end()调用必须存在于某个地方,否则我是我的进程未从我正在写的输入中接听。

每当我收到引擎的输出后尝试将"isready\n"写入子进程时,都会遇到此错误

错误[ERR_STREAM_WRITE_AFTER_END]:结束后写入

整个事情看起来像这样:

const engineExePath = 'C:\\Users\\chopi\\Desktop\\chess-engine\\maestro\\uci.exe';
const childProcess = require('child_process');
const spawn_options = {
    cwd: null,env: null,detached: false
}

const enginestream = childProcess.spawn(engineExePath,[],spawn_options);
enginestream.stdout.on('data',function (data) {

    var result = data.toString();

    if (result == 'id name Maestro\r\nid author dvdutch\r\nuciok\r\n') {
        //Here,we are listening to the response from the engine,and are Now ready to spit back a message to it.
        //This is where the error is occurring
        enginestream.stdin.write('isready\n');
    } else {
        console.log('no match');
    }

});

enginestream.stdin.write('uci\n');
enginestream.stdin.end();

我尝试过的操作:当子进程通过以下方式关闭其流时,我试图调用enginestream.stdin.end()

enginestream.on('close',(code) => {
  enginestream.stdin.end();
});

但是,当我这样做时,似乎并没有促进Node文件与子进程之间的任何通信,就像enginestream.stdin.end()根本没有被调用一样。此方法的整个集成如下所示:

const engineExePath = 'C:\\Users\\chopi\\Desktop\\chess-engine\\maestro\\uci.exe';
const childProcess = require('child_process');
const spawn_options = {
    cwd: null,and are Now ready to spit back a message to it.
        enginestream.stdin.write('isready\n');
    } else {
        console.log('no match');
    }

});

enginestream.on('close',(code) => {
  enginestream.stdin.end();
});

enginestream.stdin.write('uci\n');

我想知道的是 促进子进程和Node文件间的消息ping-ponging的正确方法是什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)