Search code examples
node.jsprotocol-buffersdecodeprotobufjs

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


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.


Solution

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