繁体   English   中英

NodeJS:在没有人工交互的情况下向持久子进程的标准输入发送消息?

[英]NodeJS: Send message to persistent child process's stdin without human interaction?

要求

我尝试将自定义消息发送到持久子进程的标准输入。 子进程不是节点进程,而是任意程序。 子进程使用 REPL 交互式提示来接受用户输入并将结果打印到标准输出,标准输出通过管道返回到父进程。 我需要能够不断地向孩子发送消息并始终如一地获得结果。

我知道我们可以使用fork()向基于 NodeJS 的子进程发送消息,但这不适用于非节点进程。

尝试 1:将父标准输入管道到子标准输入

我最初的尝试是允许用户从父进程的 stdin 输入消息,并将其通过其子进程进行管道传输。 这有效,但最终不是我想要的。

这是父进程: hello_childstdin.js

const {join} = require('path');
const {spawn} = require('child_process');

const child = spawn('/usr/local/bin/python3', [join(__dirname, 'hello_childstdin.py')]);

process.stdin.pipe(child.stdin);

child.stdout.on('data', (data) => {
    console.log(`child stdout: \n${data}`);
});

child.stderr.on('data', (data) => {
    console.log(`child stderr: \n${data}`);
});

这是子进程: hello_childstdin.py

while True:
    cmd = input('Enter command here (hello, bye, do it):')
    print('cmd: {}'.format(cmd))
    msg = cmd+': done\n' if cmd in ('hello', 'bye', 'do it') else 'undefined cmd: {}'.format(cmd)
    with open('/path/to/hello_childstdin.txt', 'a') as f:
        f.write(msg)
    print('msg: {}'.format(msg))

但是,我真正想要的是在没有人工干预的情况下直接向子进程的标准输入发送消息

我尝试了以下但失败了。

尝试 2:管道然后写入父标准输入。

父进程: hello_childstdin.js

const {join} = require('path');
const {spawn} = require('child_process');

const child = spawn('/usr/local/bin/python3', [join(__dirname, 'hello_childstdin.py')]);

process.stdin.pipe(child.stdin);

// Trying to write to parent process stdin
process.stdin.write('hello\n');

child.stdout.on('data', (data) => {
    console.log(`child stdout: \n${data}`);
});

child.stderr.on('data', (data) => {
    console.log(`child stderr: \n${data}`);
});

尝试 3:写入子标准输入。

父进程: hello_childstdin.js

const {join} = require('path');
const {spawn} = require('child_process');

const child = spawn('/usr/local/bin/python3', [join(__dirname, 'hello_childstdin.py')]);

process.stdin.pipe(child.stdin);

// Trying to write to parent process stdin
child.stdin.write('hello\n');

child.stdout.on('data', (data) => {
    console.log(`child stdout: \n${data}`);
});

child.stderr.on('data', (data) => {
    console.log(`child stderr: \n${data}`);
});

尝试 4

看到 child.stdin 的文档解释:

如果子进程正在等待读取其所有输入,则在通过 end() 关闭此流之前,它不会继续。

然后我在我的父进程中尝试了以下操作。

// ... same as above ...

child.stdin.write('hello\n');
child.stdin.end();

// ... same as above ...

这结束子并且不写消息。

与未分叉的子进程进行双工通信的正确方法是什么?

想通了:我可以将可读流推送给孩子。

...

const stream = require('stream');

...

var stdinStream = new stream.Readable();
stdinStream.push('hello\n');  // Add data to the internal queue for users of the stream to consume
stdinStream.pipe(child.stdin);

感谢这个答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM