目标
在Windows&Linux中,Mac理论也可以,执行child_process exec时,中文可以正常显示。
实现
1. 安装iconv-lite
1
| npm install iconv-lite -S
|
2. 具体代码
runExec.js
内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const exec = require('child_process').exec; const os = require("os"); const iconv = require('iconv-lite'); const encoding = os.platform() == 'win32' ? 'cp936' : 'utf-8'; const binaryEncoding = 'binary';
const runExec = (cmd) => { return new Promise((resolve, reject) => { exec(cmd, { encoding: binaryEncoding }, function(error, stdout, stderr) { if (error) { reject(iconv.decode(new Buffer(error.message, binaryEncoding), encoding)); } else { resolve(iconv.decode(new Buffer(stdout, binaryEncoding), encoding)); } }); }) } export default runExec
|
调用方
1 2 3 4 5 6
| import runExec from 'runExec.js' runExec('echo "中文测试"').then(res => { console.log('执行成功', res); }).catch(err => { console.log('执行失败', err); })
|
亲测在Windows 11
和Kali Linux
下都能正常显示中文,其他系统如有不支持,只需更改encoding
即可