我有一个 Node js 脚本,它从服务器获取一些数据并获取可读字符串。
我用来将十六进制转换为字符串的函数如下:
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
这适用于大多数字符串,但当涉及到外文字母时,我无法让它工作。
例如:
以下内容:
是我想要在console.log cmd窗口中显示的字符串。
十六进制如下(显然......):
D9 87 D9 86 DA AF 20 D8 B3 D9 88 D8 A7 D8 B1 5B
这就是在cmd中输出以下内容:
Ù?Ù?Ú¯ سÙ?ار
我怎样才能让它工作,以便它向我显示正确的输出,即图像中显示的内容?
最佳答案
这对我来说看起来像 UTF-8 see reference here
一种方法是使用 \u
转义每个字符,如下所示,console.log('\u00d9\u0087\u00D9');
在 Node 的 .12 版本中,有 this option
还有一些非常酷的模块可以为您执行此操作,请查看 the utf8 module
//from docs
// → '\xA9'
utf8.decode('\xF0\x90\x80\x81');
关于node.js - Node js 解析外来字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29479644/