NodeJS 在Windows下使用child_process spawn或exec时编码错误

rekjcdws  于 2023-06-22  发布在  Node.js
关注(0)|答案(4)|浏览(404)

在Windows CMD中使用dir命令将产生以下输出:

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将导致:

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

下面是我的Node Code:

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);
    }
});
4ioopgfo

4ioopgfo1#

我通过在我的exec命令开始时添加cmd /c chcp 65001>nul &&(此命令将cmd的控制台输出设置为utf-8)来修复它,所以你看起来像cmd /c chcp 65001>nul && dir,它应该可以工作。
如果你写跨平台可以使用process.platform,来确定你什么时候需要,类似这样的东西:

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

child = exec(cmd, //...
  • 即使dir命令不是“跨平台”。
wkyowqbh

wkyowqbh2#

我通过下面的代码解决了它(简体中文),不知道其他语言的编码页面,也许你可以从微软网站上找到它:

const encoding          = 'cp936';
  const binaryEncoding    = 'binary';

  function iconvDecode(str = '') {
      return iconv.decode(Buffer.from(str, binaryEncoding), encoding);
  }

  const  { exec } = require('child_process');  
  exec('xxx', { encoding: 'binary' }, (err, stdout, stderr) => {
        const result = iconvDecode(stdout);
        xxx
  });
tct7dpnv

tct7dpnv3#

来自http://www.nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
还有第二个可选参数用于指定多个选项。默认选项为

{ encoding: 'utf8',
  timeout: 0,
  maxBuffer: 200*1024,
  killSignal: 'SIGTERM',
  cwd: null,
  env: null }

也就是说,Node默认为utf8,而Windows对于不同的语言版本有不同的代码页。

ubby3x7f

ubby3x7f4#

const child = spawn("clip");
child.stdin.setDefaultEncoding("utf16le");
child.stdin.write("سلام دوستان");
child.stdin.end();

相关问题