解决nodejs的child_process spawn 或者exec使用windows cmd返回乱码问题

2,636 阅读1分钟

解决方案

修改cmd的pagecode

概要

使用cmd /c chcp 65001>nul && 你的命令来修改cmd的pagecode,使其输出utf-8的输出。

代码

    function exec(command: string) {
        const result = execFileSync('cmd', [`/C chcp 65001>nul && ${command}`], {
            windowsHide: true
        })
        return result
    }

手动解码

概要

查询出你的cmd的pagecode,然后使用iconv-lite来将buffer解码为字符串。

步骤

  1. 在cmd中输入chcp,查询出你的pagecode
  2. 将exec或者child_process spawn 的option下的encoding设置为buffer
  3. 将步骤2中获取到的buffer使用iconv-lite来解码

代码

    function exec(command: string) {
        function iconvDecode(buffer: Buffer) {
            let encodeing = 'cp936'
            return iconv.decode(buffer, encoding);
        }
        const result = execFileSync('cmd', [`/C ${command}`], {
            windowsHide: true
        })
        return iconvDecode(result)
    }

其他解释

pagecode

  • 什么是code page?一种旧的编码系统。zh.wikipedia.org/wiki/%E4%BB…
  • 如何查询code page? 使用chcp命令
  • 如何切换code page?例如切换utf-8:chcp 65001

最后

第一篇文章,大家多多支持,欢迎评论,我会及时解答。