Windows 下处理 Node.js child_process.exec 输出乱码问题
当 Windows 系统的区域设置或命令行终端使用非 UTF-8 编码(例如:GBK 或 CP936)时,Node.js 内置的 child_process.exec 默认会将输出当作 UTF-8 处理,这可能会导致输出乱码。
解决方案
可以按照以下步骤解决这个问题:
- 使用 exec 的
encoding
参数,将输出设置为buffer
,这样输出不会自动转换为字符串。 - 使用类似
iconv-lite
的库,根据实际编码(如cp936
或gbk
)手动解码 buffer。
示例
下面是一个完整的示例文件 [example.ts],请按照如下内容创建该文件:
import { exec } from 'child_process';
import iconv from 'iconv-lite';
// 执行命令时将 encoding 设为 'buffer'
exec('dir', { encoding: 'buffer' }, (error, stdout, stderr) => {
if (error) {
console.error(`执行命令出错: ${error}`);
return;
}
// 假定 Windows 系统使用 CP936 编码(常见于中文系统)
const output = iconv.decode(stdout, 'cp936');
console.log('命令输出:', output);
});
安装依赖
在使用前,请确保安装了 iconv-lite
包,可以使用以下命令进行安装:
npm install iconv-lite
总结
通过将 child_process.exec
的输出设置为 buffer,并采用 iconv-lite
对输出进行手动解码,就可以避免 Windows 电脑上由于非 UTF-8 编码造成的输出乱码问题。