Read protobuf messages in Nodejs / JavaScript

I have a SQLite database that stores serialized protobuf messages. I need an easy way to look at what’s in these messages. Reading the protobuf messages with JavaScript seems a good choice for me because I can see everything in JSON.

Here is how to read a protobuf message in JavaScript and display as JSON:

ProtoBuf = require('protobufjs');
sqlite3 = require('sqlite3').verbose();

// Read the proto file
var builder = ProtoBuf.loadProtoFile("/path/to.proto");
JS = builder.build("my_proto_package");

// Open SQLite database, since that's where my protobuf messages are stored
var db = new sqlite3.Database('my_sqlite.db');
db.each("SELECT proto as p FROM tbl LIMIT 100", function(err, row){
	var msg = JS.MyMessage.decode(row.p);
	console.log(msg);
});

row.p is just a buffer. So if you have the protobuf message in a file, you can do this instead:

require('fs')
fs.readFile("file", function(err, data){
	console.log(JS.MyMessage.decode(data));
});

Do see the ProtoBuf.js example, it is very helpful: https://github.com/dcodeIO/ProtoBuf.js/tree/master/examples/protoify

Advertisements

One thought on “Read protobuf messages in Nodejs / JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s