问题描述
我正在使用Node JS子进程来运行命令,我需要以某种方式在提示时自动输入一些文本,然后从我的stdout
内部自动按Enter键,不确定如何执行此操作...
var child = spawn('COMMAND-TO-RUN',{
shell: true
});
child.stdout.on('data',function (data) {
// when prompted in the terminal,need to input something automatically from here...
console.log(data)
console.log("STDOUT:",data.toString());
});
更新
我已经尝试使用child.stdin.write
,并且在终端提示输入SSH密码的问题下,此操作不起作用,因为我试图通过以下方式自动向终端输入密码: JS,不确定为什么这行不通。
解决方法
您可以将子级的stdin和stderr传递给父进程。例如:
var child = spawn('ps',{
shell: true
});
child.stdout.on('data',function (data) {
// when prompted in the terminal,need to input something automatically from here...
process.stdout.write('Something I want to print\n\n');
console.log(data)
console.log("STDOUT:",data.toString());
});