0

我是 protobuf 的新手,想通过网络或文件传递一些数据来试验它,例如

2-byte unsigned int: 15
2-byte unsigned int: 15 and -1
4-byte unsigned int: 256, and then a string "Peter"
4-byte unsigned int: 256, and then two strings "Peter", "Mary"
4-byte signed int: (3, 4) as a point
4-byte signed int: a point above twice, such as (3, 4) and (10, 11) as a line
4-byte signed int and a string: the line above, and a name for this line

字节可以由 Python / Ruby 写入文件,然后由 JavaScript 读回吗?(或者可以全部用 JavaScript 编写)。

我认为能够在本地网站上传递它可能要复杂得多?如果是这样,将其写入文件并能够读回就可以了。怎么可能做到?

4

1 回答 1

0

我发现使用protobuf.js要简单得多,我们不需要使用protoc哪个编译器命令行工具。我发现让 Python 或 C++ 版本运行起来很困难,因为它涉及 Python2 与 Python3,pip并且缺少库。

所以只需关注protobuf.js 网站,我已经包含了使其工作的基本最低要求。

我们可以从 Google 的网站上阅读有关如何制作.proto文件的所有信息。

脚步:

创建一个空文件夹并安装 protobufjs。nvm如果需要,请使用Google for (可选)和 Node.js 和 npm。

mkdir TryProtobufJS
cd TryProtobufJS
npm i protobufjs

现在,创建这 3 个文件:

// awesome.proto
package awesomepackage;
syntax = "proto3";

message AwesomeMessage {
    int32 num = 1;
    string awesome_field = 20; // becomes awesomeField
}
// write.js

const fs = require("fs");
const protobuf = require("protobufjs");

protobuf.load("awesome.proto", function (err, root) {
  if (err) throw err;

  const AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage");

  const payload = { num: 15, awesomeField: "ABC" };
  console.log("payload", payload);

  const errMsg = AwesomeMessage.verify(payload);
  if (errMsg) throw Error(errMsg);

  const message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary

  // Encode a message to an Uint8Array (browser) or Buffer (node)
  const buffer = AwesomeMessage.encode(message).finish();

  console.log(buffer);
  fs.writeFileSync("awesome.dat", buffer);
});
// read.js

const fs = require("fs");
const protobuf = require("protobufjs");

protobuf.load("awesome.proto", function (err, root) {
  if (err) throw err;

  const AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage");

  const buffer = fs.readFileSync("awesome.dat");
  console.log(buffer);

  // Decode an Uint8Array (browser) or Buffer (node) to a message
  const message = AwesomeMessage.decode(buffer);

  // Convert the message back to a plain object
  const object = AwesomeMessage.toObject(message, {
    longs: String,
    enums: String,
    bytes: String,
    // see ConversionOptions
  });
  console.log("object", object);
});

现在运行文件write.js

node write.js

它将创建一个数据文件:awesome.dat.

# screen output

payload { num: 15, awesomeField: 'ABC' }
<Buffer 08 0f a2 01 03 41 42 43>

在 Mac 上,您可以使用十六进制转储它来查看它:

hexdump -C awesome.dat

现在,要“取回数据”,请使用

node read.js
# screen output

<Buffer 08 0f a2 01 03 41 42 43>
object { num: 15, awesomeField: 'ABC' }

如果我使用 Node.js v14,由于某种原因,它在 MacBook Air M1 上对我不起作用,但 Node v15 和 v16 可以工作。

另外需要注意的是,我们在 Node.js 中写入文件和读取文件时,由于以下原因,我们没有指定编码:

  1. writeFileSync:如果数据是缓冲区,则忽略编码选项。
  2. readFileSync:如果指定了编码选项,则此函数返回一个字符串。否则它返回一个缓冲区。
于 2021-05-01T11:57:41.660 回答