Hyperledger Fabric API returns 缓冲区类型数据,我如何将缓冲区转换为此数据的字符串 javascript

Hyperledger Fabric API returns a buffer type data, how do i convert buffer to string of this data in javascript

我正在 hyperledger fabric (node.js SDK) 上构建区块链。

https://hyperledger.github.io/fabric-sdk-node/release-1.4/global.html#BlockchainInfo__anchor

我调用 api BlockchainInfo 并得到一个 json 格式的响应,其中包括 currentBlockHash

官方文档显示data type of currentBlockHash 数组<字节>

比如下面的数据

我想将此缓冲区转换为字符串,但不知道该怎么做。

感谢您阅读问题。

{ buffer:
   { type: 'Buffer',
     data:
      [ 8,
        207,
        230,
        17,
        18,
        32,
        124,
        143,
        73,
        40,
        171,
        42,
        251,
        237,
        193,
        138,
        36,
        92,
        58,
        57,
        254,
        56,
        144,
        96,
        54,
        201,
        242,
        64,
        10,
        111,
        150,
        28,
        198,
        187,
        196,
        118,
        97,
        160,
        26,
        32,
        16,
        160,
        154,
        19,
        11,
        179,
        147,
        11,
        38,
        16,
        150,
        190,
        126,
        17,
        121,
        123,
        200,
        7,
        71,
        27,
        241,
        103,
        54,
        188,
        196,
        248,
        178,
        88,
        48,
        115,
        186,
        133 ] },
  offset: 6,
  markedOffset: -1,
  limit: 38,
  littleEndian: true,
  noAssert: false }

这里是原始响应数据

{"height":{"low":291663,"high":0,"unsigned":true},"currentBlockHash":{"buffer":{"type":"Buffer","data":[8,207,230,17,18,32,124,143,73,40,171,42,251,237,193,138,36,92,58,57,254,56,144,96,54,201,242,64,10,111,150,28,198,187,196,118,97,160,26,32,16,160,154,19,11,179,147,11,38,16,150,190,126,17,121,123,200,7,71,27,241,103,54,188,196,248,178,88,48,115,186,133]},"offset":6,"markedOffset":-1,"limit":38,"littleEndian":true,"noAssert":false},"previousBlockHash":{"buffer":{"type":"Buffer","data":[8,207,230,17,18,32,124,143,73,40,171,42,251,237,193,138,36,92,58,57,254,56,144,96,54,201,242,64,10,111,150,28,198,187,196,118,97,160,26,32,16,160,154,19,11,179,147,11,38,16,150,190,126,17,121,123,200,7,71,27,241,103,54,188,196,248,178,88,48,115,186,133]},"offset":40,"markedOffset":-1,"limit":72,"littleEndian":true,"noAssert":false}}

我认为 JSDoc 在这种情况下具有误导性。我认为 currentBlockHash 实际上是一个 Node.js 缓冲区(或者可能是一个模拟缓冲区行为的 protobuf 实现)。您可以通过调用 currentBlockHash.toString().

将 Buffer 转换为字符串

我观察到一些情况,在 protobuf Buffer 实现上调用 toString() 会给出调试字符串而不是缓冲区内容的字符串表示形式,因此为了安全起见,我倾向于指定一个编码参数。

在哈希的情况下,无论如何将它视为十六进制字符串而不是 utf8(这将是默认值)可能更方便,所以我会尝试 currentBlockHash.toString('hex')

有关缓冲区的更多信息,请参阅此处:https://nodejs.org/docs/latest-v10.x/api/buffer.html