如何用Node.js child_process实现CLI命令执行时的密钥交互输入
要实现带交互输入的CLI命令调用,不推荐使用child_process.exec,该方法为缓冲式输出,无法处理实时的标准输入交互,建议使用child_process.spawn直接操作进程的标准输入/输出流,具体实现代码如下:
const { spawn } = require('child_process'); // 定义要执行的命令和参数 const command = 'helium-wallet'; const args = ['create', 'basic', '--seed', 'mobile', '--output', './wallet-mobile.key']; // 替换为你实际要输入的密钥 const passphrase = 'your_secure_passphrase'; // spawn子进程,配置标准输入输出为管道模式 const child = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'], // 可选:如果命令需要在shell环境运行可以设置为true shell: false }); // 监听命令的标准输出,匹配密钥输入提示 child.stdout.on('data', (data) => { const output = data.toString(); console.log('命令输出:', output); // 请根据helium-wallet实际的输入提示文本修改匹配规则,比如提示为"Enter passphrase:" if (output.includes('Enter passphrase')) { // 写入密钥加换行符(模拟用户输入后按回车) child.stdin.write(`${passphrase}\n`); } // 如果需要二次确认密钥,添加对应匹配逻辑 if (output.includes('Confirm passphrase')) { child.stdin.write(`${passphrase}\n`); // 所有输入完成后结束标准输入流 child.stdin.end(); } }); // 监听标准错误输出 child.stderr.on('data', (data) => { console.error('命令错误:', data.toString()); }); // 监听进程退出事件 child.on('exit', (code) => { if (code === 0) { console.log('钱包创建成功'); } else { console.log('命令执行失败,退出码:', code); } });
注意事项
- 代码中匹配的输入提示文本需要和
helium-wallet实际输出的提示完全对应,否则无法触发自动输入,你可以先手动执行一次命令,确认提示文本的准确内容后再修改匹配规则。 - 如果需要处理更复杂的多步交互场景,可以使用第三方库
execa,它对进程交互做了封装,写法更简洁,无需手动监听流事件。
内容的提问来源于stack exchange,提问作者Dian
相关产品推荐
相关产品推荐

