首页 > 解决方案 > 从字节缓冲区转换为字符串,然后在 NodeJS / Javascript 中转换回字节

问题描述

就像标题所述,我只是想在一个字符串中编码一些字节,然后将它们解码回字节。将 Uint8 字节数组转换为字符串然后再转换回数组并不完美。我只是想知道我应该在转换中使用什么编码以使其正确发生。

我试试这个作为一个虚拟的例子:

  var bytes = serializeToBinary(); // giving me bytes 
  console.log('bytes type:'+ Object.prototype.toString.call(bytes));
  console.log('bytes length:'+ bytes.length);

  var bytesStr = bytes.toString('base64'); // gives me a string that looks like '45,80,114,98,97,68,111'
  console.log('bytesStr length:'+ bytesStr.length);
  console.log('bytesStr type:'+ Object.prototype.toString.call(bytesStr));

  var decodedbytesStr = Buffer.from(bytesStr, 'base64');
  console.log('decodedbytesStr type:'+ Object.prototype.toString.call(decodedbytesStr));
  console.log('decodedbytesStr length:'+ decoded.length);

输出:

bytes type:[object Uint8Array]
bytes length:4235
bytesStr type:[object String]
bytesStr length:14161
decodedbytesStr type:[object Uint8Array]
decodedbytesStr length:7445

decodedbytesStr 长度和字节长度不应该相同吗?

标签: javascriptarraysstringencoding

解决方案


TypedArray不支持.toString('base64')。该base64参数被忽略,您只需获得数组值的字符串表示形式,用逗号分隔。这不是base64 字符串,因此Buffer.from(bytesStr, 'base64')没有正确处理它。

您想改为调用.toString('base64')a Buffer。创建时bytesStr,只需Buffer从您的Uint8Array第一个开始构建:

var bytesStr = Buffer.from(bytes).toString('base64');

推荐阅读