Cucumber测试执行Shell命令输出乱码问题求助
问题原因及解决方案
核心根源:终端输出编码不匹配
用Node.js的child_process.exec执行Shell命令时,默认编码和系统终端编码不一致(比如Windows下GBK/GB2312 vs UTF-8),或者子进程输出的字节流未正确解码,就会出现乱码。结合你的场景(Cucumber+WDIO+Appium),以下是具体解决办法:
1. 显式指定exec的编码参数
调用exec时直接指定编码,强制将输出转译为可读格式:
const { exec } = require('child_process'); // Windows系统用'gbk',Linux/macOS用'utf8' exec('ping baidu.com', { encoding: 'gbk' }, (error, stdout, stderr) => { if (error) { console.error(`执行错误: ${error}`); return; } console.log(`输出内容: ${stdout}`); console.error(`错误信息: ${stderr}`); });
2. 手动解码字节流
如果指定编码参数无效,可直接获取Buffer输出后手动解码:
exec('ping baidu.com', { encoding: 'buffer' }, (error, stdout, stderr) => { if (error) { console.error(error); return; } // 根据系统自动适配编码 const decodedOutput = process.platform === 'win32' ? stdout.toString('gbk') : stdout.toString('utf8'); console.log(decodedOutput); });
3. 替换exec为spawn处理持续输出
ping这类持续输出的命令,exec的缓冲机制可能加剧乱码问题,改用spawn实时处理输出流:
const { spawn } = require('child_process'); const pingProcess = spawn('ping', ['baidu.com']); // 实时处理标准输出 pingProcess.stdout.on('data', (data) => { const output = process.platform === 'win32' ? data.toString('gbk') : data.toString('utf8'); console.log(output); }); // 实时处理错误输出 pingProcess.stderr.on('data', (data) => { const errorOutput = process.platform === 'win32' ? data.toString('gbk') : data.toString('utf8'); console.error(errorOutput); }); pingProcess.on('close', (code) => { console.log(`ping进程退出,码值: ${code}`); });
4. 检查WDIO日志编码配置
如果乱码出现在测试报告或日志中,需确保wdio.conf.js的日志编码正确:
exports.config = { // ...其他配置 reporters: [ ['spec', { showPreface: false, stdout: process.stdout.setEncoding('utf8') }] ] };
额外排查点
- 查看系统终端默认编码:Windows输入
chcp(通常为936对应GBK),Linux/macOS输入echo $LANG(一般为UTF-8)。 - 调整Node.js环境编码:Linux/macOS启动测试前执行
export LANG=en_US.UTF-8,Windows执行set LANG=en_US.UTF-8。
内容的提问来源于stack exchange,提问作者Mr. E
相关产品推荐
相关产品推荐

