How to decode encoded protocol buffer data with a .proto file in node.js

7.6k views Asked by At

I am new to protocol buffer and I am trying to decode data from an api response.

I get encoded data from the api response and I have a .proto file to decode the data, how do I decode the data in nodeJS. I have tried using protobuf.js but I am very confused, I have spent hours trying to solve my problem looking at resources but I cannot find a solution.

1

There are 1 answers

2
Terry Lennox On BEST ANSWER

Protobufjs allows us to encode and decode protobuf messages to and from binary data, based on .proto files.

Here's a simple example of encoding and then decoding a test message using this module:

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();

And the .proto file:

package testpackage;
syntax = "proto3";

message testMessage {
    uint32 timestamp = 1;
    string message = 2;
}