简体   繁体   中英

How to load a protocol buffer binary file in javascript?

I have generated a binary file containing some data using protobuf in Python, and I need to load the binary file now in Javascript and read its content. I tried to use FileReader() but I wasn't able to succeed. How can I do this?

You can make use of protobufjs .

Here's an example in JavaScript:

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

// Load the binary data
const binaryData = fs.readFileSync('your-protocol-buffer-file.bin');

// Load the root of the protocol buffer definition
const root = protobuf.Root.fromJSON(yourProtoJSON);

// Look up the desired message type
const MyMessageType = root.lookupType('MyMessageType');

// Decode the binary data using the message type
const message = MyMessageType.decode(binaryData);

// The message object is a JavaScript object that represents the data in the binary file
console.log(message);

You will need to have the Protocol Buffer definition (.proto file) that was used to generate the binary file in order to use protobufjs to decode the data.

For more information on protobufjs, you can visit https://github.com/protobufjs/protobuf.js .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM