我发现使用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 中写入文件和读取文件时,由于以下原因,我们没有指定编码:
- writeFileSync:如果数据是缓冲区,则忽略编码选项。
- readFileSync:如果指定了编码选项,则此函数返回一个字符串。否则它返回一个缓冲区。