const { exec } = require("child_process");
const iconv = require("iconv-lite");
const encoding = "cp936";
const bufferEncoding = "binary";
exec(`ipconfig`, { encoding: bufferEncoding }, function (err, stdout, stderr) {
if (err) {
console.log(iconv.decode(Buffer.from(err.stack, bufferEncoding), encoding));
console.log(iconv.decode(Buffer.from(err.message, bufferEncoding), encoding));
} else {
console.log(iconv.decode(Buffer.from(stdout, bufferEncoding), encoding));
console.log(iconv.decode(Buffer.from(stderr, bufferEncoding), encoding));
}
});
child_process exec 乱码
于 2022-06-29 22:56:58 首次发布
该博客主要展示了如何使用Node.js的`child_process`模块执行外部命令,并结合`iconv-lite`库处理不同字符编码的问题。在示例中,`ipconfig`命令的输出被转换为`cp936`编码,以正确解码非ASCII字符。博客讨论了在处理跨平台命令输出时的编码挑战和解决方案。
摘要由CSDN通过智能技术生成