使用Node.js child_process.spawn实现CLI交互自动输入失败如何解决?
问题原因
子进程启动后立刻写入所有输入,此时CLI工具尚未完成初始化、未进入等待用户输入的状态,输入内容会被丢弃,无法匹配到对应的输入步骤。
修复方案
推荐监听子进程的标准输出,匹配到CLI输出的输入提示后再写入对应内容,参考实现如下:
const childprocess = require('child_process'); // 替换为你的CLI脚本启动命令和参数 const child = childprocess.spawn('node', ['cli脚本路径', ...myArgs], { // Windows环境运行建议开启shell配置 shell: process.platform === 'win32' }); // 按顺序定义要输入的内容 const inputQueue = ['step1', 'step2']; let currentInputIndex = 0; child.on('error', (err) => { console.error('子进程错误: ', err); }) child.stdout.setEncoding('utf8'); child.stdout.on('data', (data) => { console.log('stdout输出: ' + data); // 此处替换为你的CLI实际输出的输入提示文本,比如"请输入步骤名称:" if (data.includes('请输入步骤名称') && currentInputIndex < inputQueue.length) { child.stdin.write(`${inputQueue[currentInputIndex]}\n`); currentInputIndex++; // 所有输入写入完成后关闭stdin if (currentInputIndex === inputQueue.length) { child.stdin.end(); } } }); // 监听标准错误输出方便排查问题 child.stderr.setEncoding('utf8'); child.stderr.on('data', (data) => { console.error('stderr输出: ', data); }); child.on('exit', (code) => { console.log('子进程执行结束,退出码:', code); });
如果你的CLI使用了inquirer等依赖终端交互的库,无法通过普通spawn触发输入识别,可以改用node-pty包模拟真实终端环境运行子进程。
如果场景不需要严格匹配输入时序,也可以直接将所有输入拼接后通过管道一次性传入:
const childprocess = require('child_process'); const allInput = inputQueue.join('\n'); const child = childprocess.exec(`node cli脚本路径 ${myArgs.join(' ')}`, (err, stdout, stderr) => { console.log('执行结果:', stdout); console.error('错误输出:', stderr); }); // 将所有输入写入子进程stdin child.stdin.write(allInput); child.stdin.end();
内容的提问来源于stack exchange,提问作者BalB
相关产品推荐
相关产品推荐

