gpt4 book ai didi

javascript - 如何从自定义 Node REPL 获取子进程中的输入

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:43 25 4
gpt4 key购买 nike

我正在尝试创建一个 Node repl,并希望生成一个子进程,该子进程可以接受用户输入,然后将控制权返回给 repl。

...主 repl 文件的内容 (a.js)

!function(){
var repl = require("repl"),
spawn = require('child_process').spawn;

function eval(cmd, context, filename, callback) {

var child = spawn('node', ['./b.js']);

child.stdout.pipe(process.stdout);
child.stdin.pipe(process.stdin);

child.on('close', function (code) {
console.log('closing')
callback(code, 'closing callback');
});

}

repl.start({
prompt: 'repl> ',
input: process.stdin,
output: process.stdout,
eval: eval
}).on('exit', function () {
process.exit();
});

}();

...子进程中调用的脚本内容(b.js)

!function(){

promptly = require('promptly');

promptly.prompt('some question: ', function (err, answer) {
console.log(answer);
process.exit();
});

}();

当我运行node b时,一切都按预期进行......

$ node b
some question: something
something
$

但是从 repl 调用,它进入循环,不断询问问题,永远不会返回到 repl...

$ node a
repl> anything
some question: my answer
some question: another answer
some question: etc...

看起来stdin没有在子进程中被捕获,并且仍在repl中被捕获。

如何将控制权传递给子进程,直到完成,然后传递回父进程?

n.b.我愿意使用任何其他方式创建子进程。

最佳答案

a.js 进行一些更改应该可以实现此目的。您需要使用 process.stdin.pipe(child.stdin);

将主 repl 进程的 stdin 输入传输到子进程的 stdin

要从子进程取回数据,您需要使用 child.stdout.pipe(process.stdout); 将 child.stdout 通过管道传输到 process.stdin

也许有更好的方法来跟踪子进程。但我添加了一个标志来标记是否生成子进程,并在子进程关闭时重置它。

最后,当子进程结束时,使用 process.stdin.resume(); 恢复主进程 stdin,否则 repl 将在下一个输入时停止。

!function(){
var repl = require("repl"),
spawn = require('child_process').spawn;

var child_spawned = false;
function eval(cmd, context, filename, callback) {
// don't start a new child process if one is already running
if(child_spawned) return;

var child = spawn('node', ['./b.js']);
child_spawned = true;

// pipe child output back up to parent process
child.stdout.pipe(process.stdout);
// pipe the main process input to the child process
process.stdin.pipe(child.stdin);

child.on('close', function (code) {
console.log('closing')
callback(code, 'closing callback');

// mark child process as closed
child_spawned = false;

// resume the main process stdin after child ends so the repl continues to run
process.stdin.resume();
});

}

repl.start({
prompt: 'repl> ',
input: process.stdin,
output: process.stdout,
eval: eval
}).on('exit', function () {
process.exit();
});

}();

关于javascript - 如何从自定义 Node REPL 获取子进程中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31632427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com