【发布时间】:2018-03-18 03:03:22
【问题描述】:
我知道解决方案很简单,但我要花一个小时才能解决问题。
在 Windows 10 中,如果我启动命令“dir”,我会得到以下结果:
Il volume nell'unità D non ha etichetta.
在 Node js 中,我尝试以这种方式执行 dir 命令:
var child = exec('dir', {'encoding': 'UTF-8'}, (err, stdout, stderr) => {
console.log(stdout);
});
我得到了这个结果: Il volume nell'unit. C non ha etichetta.
啊,该死的重音字母!
我尝试使用 UTF-16,然后转换为字符串:
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 volume nell'unit。C non ha etichetta。”
你能帮我解决这个问题吗? 我做错了什么?
exec 命令似乎不接受 UTF-8 编码 事实上,如果我运行这个脚本来强制从 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 throw Error('检测到无效的 UTF-8');
有什么想法吗?
【问题讨论】: