【问题标题】:How to save returned protobuf object in nodejs?如何在nodejs中保存返回的protobuf对象?
【发布时间】:2019-10-02 13:35:54
【问题描述】:

在我的代码中,一个函数返回一个 protobuf 对象,我想将它保存在文件 xyz.pb 中。
当我尝试使用 fs.writefilesync 保存它时,它并没有保存它。

它本质上是圆形的。所以,我尝试使用 circular-json 模块来保存它,以确认它里面是否有任何东西并且它有数据。

但是,由于我首先使用了 circular-json,它没有正确的信息(格式不正确)并且没有用。

如何使用 nodejs 将此 protobuf 保存在文件中?

谢谢!

【问题讨论】:

    标签: node.js hyperledger-fabric protocol-buffers


    【解决方案1】:

    你可以尝试使用流like mentioned in documentation

    如下

    const crypto = require('crypto');
    const fs = require('fs');
    const wstream = fs.createWriteStream('fileWithBufferInside');
    // creates random Buffer of 100 bytes
    const buffer = crypto.randomBytes(100);
    wstream.write(buffer);
    wstream.end();
    

    或者您可以将缓冲区转换为 JSON 并将其保存在文件中,如下所示:

    const crypto = require('crypto');
    const fs = require('fs');
    const wstream = fs.createWriteStream('myBinaryFile');
    // creates random Buffer of 100 bytes
    const buffer = crypto.randomBytes(100);
    wstream.write(JSON.stringify(buffer));
    wstream.end();
    

    如果您的应用程序逻辑不需要使用同步特性,则不应使用writeFileSync,因为它会阻塞您的代码,直到它结束,所以要小心。 尝试使用 writeFile 或 Streams 更方便。

    【讨论】:

      【解决方案2】:

      Protocol Buffers 的目的是将强类型消息序列化为二进制格式并返回到消息中。如果要将内存中的消息写入文件,首先将消息序列化为二进制,然后将二进制写入文件。

      NodeJS Buffer docs

      NodeJS write binary buffer into a file

      Protocol Buffers JavaScript SDK Docs

      它应该看起来像这样:

      const buffer = messageInstance.serializeBinary()
      fs.writeFile("filename.pb", buffer, "binary", callback)
      

      【讨论】:

      • 它抛出一个错误,因为“serializeBinary 不是一个函数”。我必须为此导入任何模块或其他东西吗?谢谢
      【解决方案3】:

      我发现了如何轻松地将 protobuf 对象保存在文件中。

      将 protobuf 对象转换为缓冲区,然后保存。

      const protobuf = somefunction(); // returning protobuf object  
      const buffer = protobuf.toBuffer();  
      
      fs.writeFileSync("filename.pb", buffer);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-26
        • 2011-11-20
        • 2017-02-28
        相关资源
        最近更新 更多