我知道解决办法很简单,但现在是一个小时了。
在Windows 10中,如果启动命令"dir",将得到以下结果:
Il卷nell‘’unitàD non .
在Node 中,我尝试以这种方式执行dir命令:
var child = exec('dir', {'encoding': 'UTF-8'}, (err, stdout, stderr) => {
console.log(stdout);
});我得到了这样的结果:Il卷nell‘’unit�C non .
啊,该死的重音字母!
我尝试使用UTF-16,然后转换为string:
var child = exec('dir', {'encoding': 'UTF-16'}, (err, stdout, stderr) => {
let b: Buffer = stdout;
let o: string;
o = stdout.toString('UTF-8');
console.log(o);
});我得到了同样的诅咒结果:
"Il卷nell‘’unit�C non .“
你能帮我解决这个问题吗?我做错了什么?
实际上,如果运行此脚本强制将UTF-8转换为string,则几乎可以认为exec命令不接受UTF-8编码:
var child = exec(j.cmd, {'encoding': 'UTF-8'}, (err, stdout, stderr) => {
var utf8 = require('utf8');
var o: string = utf8.decode(stdout)
console.log(o);
});我发现了一个错误:
..\node_modules\utf8\utf8.js:194抛出错误(‘无效UTF-8检测到的’);
有什么想法吗?
发布于 2017-10-07 13:19:27
当您在命令提示符中使用dir时,呈现器知道正在使用哪个字符编码stdout,对文本字节进行解码,并使用所选字体呈现字符。
执行命令时,节点不知道正在使用哪个字符编码stdout,所以您可以告诉它。问题是你说错了。要查看是哪个字符编码,请转到chcp。但是,开箱即用的节点只支持几十个字符编码中的一些.
解决方案是告诉命令提示符使用它们的共同点。由于您从文件系统获取路径,并且文件系统(NTFS)使用Unicode字符集作为路径,所以UTF-8是一个很好的选择。
因此,这应该是可行的:
exec('@chcp 65001 >nul & dir', {encoding: "UTF-8"},
(err, stdout, stderr) => console.log(stdout));但是,chcp命令具有延迟效果,不应用于dir命令。这里有一种方法可以解决这个问题:
exec('@chcp 65001 >nul & cmd /d/s/c dir', {encoding: "UTF-8"},
(err, stdout, stderr) => console.log(stdout));运行批处理文件可能是一种更简单的方法,可以让两个单独的命令按顺序运行,但这需要设置和清理。
https://stackoverflow.com/questions/46603489
复制相似问题