Mat*_*ays 5 decode protocol-buffers node.js protobufjs
我是协议缓冲区的新手,我正在尝试从 api 响应中解码数据。
我从 api 响应中获取编码数据,并且有一个 .proto 文件来解码数据,如何在 nodeJS 中解码数据。我尝试过使用 protobuf.js 但我很困惑,我花了几个小时试图查看资源来解决我的问题,但我找不到解决方案。
Protobufjs允许我们基于 .proto 文件对 protobuf 消息与二进制数据进行编码和解码。
这是使用此模块对测试消息进行编码和解码的简单示例:
const protobuf = require("protobufjs");
async function encodeTestMessage(payload) {
    const root = await protobuf.load("test.proto");
    const testMessage = root.lookupType("testpackage.testMessage");
    const message = testMessage.create(payload);
    return testMessage.encode(message).finish();
}
async function decodeTestMessage(buffer) {
    const root = await protobuf.load("test.proto");
    const testMessage = root.lookupType("testpackage.testMessage");
    const err = testMessage.verify(buffer);
    if (err) {
        throw err;
    }
    const message = testMessage.decode(buffer);
    return testMessage.toObject(message);
}
async function testProtobuf() {
    const payload = { timestamp: Math.round(new Date().getTime() / 1000), message: "A rose by any other name would smell as sweet" };
    console.log("Test message:", payload);
    const buffer = await encodeTestMessage(payload);
    console.log(`Encoded message (${buffer.length} bytes): `, buffer.toString("hex"));
    const decodedMessage = await decodeTestMessage(buffer);
    console.log("Decoded test message:", decodedMessage);
}
testProtobuf();
和 .proto 文件:
package testpackage;
syntax = "proto3";
message testMessage {
    uint32 timestamp = 1;
    string message = 2;
}