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

问题描述

我是协议缓冲区的新手,我正在尝试从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;
}