在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使用exec或spawn将导致以下结果:
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);
}
});发布于 2020-01-08 03:51:23
我设法通过在我的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, //...即使"cross-platform".命令不是
dir命令发布于 2020-06-01 11:42:26
我通过下面的代码解决了它(简体中文),不知道其他语言的编码页面,也许你可以在微软网站上找到它:
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
});发布于 2014-02-26 14:33:35
来自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针对不同的语言版本有不同的代码页。
https://stackoverflow.com/questions/20731785
复制相似问题