获取mongo shell BinData作为字符串

时间:2018-11-30 10:57:19

标签: javascript mongodb utf-8 decode mongo-shell

如何将包含UTF-8编码文本的BinData对象转换为字符串?

我正在使用MongoDB shellmongo命令)。它基本上是Javascript交互式控制台(我认为它是SpiderMonkey),但是像Node.js中没有Buffer对象可以与BinData对象提供的十六进制或base64格式一起使用。

1 个答案:

答案 0 :(得分:1)

我可以使用从BinData到十六进制的转换,然后解析十六进制字符串。

function hex2a(hexStr) {
  var s = ''; 
  for (let i=0; i<hexStr.length; i+=2) 
    s += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
  return s;
}

hex2a(BinData(0,"aGVsbG8=").hex())
// returns "hello"

但这仅适用于ASCII。