如何在Node.js中使用.proto文件解码编码的Protocol Buffer数据

4

我对协议缓冲区还不熟悉,正在尝试从API响应中解码数据。

我从API响应获取编码数据,并有一个.proto文件来解码数据,如何在nodeJS中解码数据。我尝试使用protobuf.js,但我非常困惑,我已经花了几个小时查看资源,但找不到解决方案。

1个回答

5

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;
}

这个是可行的。但是现在protobuf可以原生支持JavaScript了。 - mradul dubey
1
它对我有效。好答案。 - SefaUn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接