从字节缓冲区转换为字符串然后在NodeJS / Javascript中转换回字节

时间:2019-07-22 18:18:06

标签: javascript arrays string encoding

就像标题状态一样,我只是尝试将某些字节编码为字符串,然后将其解码回字节。将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长度和bytes长度不应该相同吗?

1 个答案:

答案 0 :(得分:1)

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

您想改为呼叫.toString('base64')上的Buffer。创建bytesStr时,只需从您的Buffer首先构建一个Uint8Array

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