Skip to content

Latest commit

 

History

History

README.md

Deserializing objects in Node.js (a different runtime)

In this project we deserialize, the protobuf binary data which was originally serialized by a Java application.

Being able to deserialize to actual object which was serialized using a different runtime, this is the main advantage of protobuf. So protobuf is language independent, provided that you follow the same schema.

Step 1 : npm install protobufjs

Create the project and npm install protobufjs

Step 2 : Write the deserializer code

const fs = require("fs");
const protobuf = require("protobufjs");

async function main() {
    try {
        // Load the .proto file
        const root = await protobuf.load("RawDataResult.proto");

        // Get the RawDataResult message type
        const RawDataResult = root.lookupType("RawDataResult");

        // Reading the protobuf binary file which was generated by a Java application
        const binaryData = fs.readFileSync("raw_data_result.bin");

        // Decode the binary data into a message object
        const decodedMessage = RawDataResult.decode(binaryData);

        // Convert the decoded message into a plain JavaScript object
        const object = RawDataResult.toObject(decodedMessage, {
            enums: String, // Convert enums to string names
            defaults: true, // Include default values
            arrays: true, // Always set arrays, even if empty
        });

        // Log the deserialized object
        console.log("Deserialized Data:", JSON.stringify(object, null, 2));
    } catch (error) {
        console.error("Error:", error);
    }
}

main();

Step 3 : Run the deserializer

Run the deserializer.js file with node deserializer.js, and deserialized RawDataResult object would be printed to console.

"Node.js Deserializer"

References :

https://github.com/eMahtab/java-projects/tree/master/protobuf-example