如何使用 node.js 中的 .proto 文件解码编码的协议缓冲区数据

Mat*_*ays 5 decode protocol-buffers node.js protobufjs

我是协议缓冲区的新手,我正在尝试从 api 响应中解码数据。

我从 api 响应中获取编码数据,并且有一个 .proto 文件来解码数据,如何在 nodeJS 中解码数据。我尝试过使用 protobuf.js 但我很困惑,我花了几个小时试图查看资源来解决我的问题,但我找不到解决方案。

Ter*_*nox 7

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();
Run Code Online (Sandbox Code Playgroud)

和 .proto 文件:

package testpackage;
syntax = "proto3";

message testMessage {
    uint32 timestamp = 1;
    string message = 2;
}
Run Code Online (Sandbox Code Playgroud)