在 Windows 下使用 child_process spawn 或 exec 时编码错误 [英] wrong encoding when using child_process spawn or exec under Windows

查看:94
本文介绍了在 Windows 下使用 child_process spawn 或 exec 时编码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows CMD 中使用 dir 命令将导致以下输出:

Using the dir command in Windows CMD will result in the following output:

Verzeichnis von D:\workspace\filewalker

22.12.2013  17:27    <DIR>          .
22.12.2013  17:27    <DIR>          ..
22.12.2013  17:48               392 test.js
22.12.2013  17:23                 0 testöäüÄÖÜ.txt
22.12.2013  17:27    <DIR>          testÖÄÜöüäß
2 Datei(en),            392 Bytes
3 Verzeichnis(se), 273.731.170.304 Bytes frei

使用 execspawn 将导致:

Using exec or spawn will result in this:

Verzeichnis von D:\workspace\filewalker

22.12.2013  17:27    <DIR>          .
22.12.2013  17:27    <DIR>          ..
22.12.2013  17:48               392 test.js
22.12.2013  17:23                 0 test������.txt
22.12.2013  17:27    <DIR>          test�������
2 Datei(en),            392 Bytes
3 Verzeichnis(se), 273.731.170.304 Bytes frei

这是我的节点代码:

var exec = require('child_process').exec,
    child;

child = exec('dir',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

推荐答案

我设法通过添加 cmd/c chcp 65001>nul &&(此命令将 cmd 的控制台输出设置为utf-8) 在我的 exec 命令开始时,所以你看起来像 cmd/c chcp 65001>nul &&dir,它应该可以工作.

I managed to fix it by adding cmd /c chcp 65001>nul &&(this command sets cmd's console output to utf-8) at start of my exec command, so your would look like cmd /c chcp 65001>nul && dir, it should work.

如果你写跨平台可以使用process.platform,来确定你什么时候需要那个,像这样:

If you write cross-platform can use process.platform, to determine when you need that, something like that:

var cmd = "";
if (process.platform === "win32") { 
  cmd += "cmd /c chcp 65001>nul && "; 
};
cmd += "dir";

child = exec(cmd, //...

  • 即使 dir 命令不是跨平台".
    • Even though dir command is not "cross-platform".
    • 这篇关于在 Windows 下使用 child_process spawn 或 exec 时编码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆