protocol-buffers

Until recently, if you wanted to insure smooth communication between different platforms within your infrastructure you had to reserve to XML RPC. To address the issue, Facebook engineers came up with Thrift (which was donated to Apache at some point) which allows to define data types and service interface to build client and server in various languages to get them talking to each other.

If that feels like an overkill for you, have a look at Google’s Protocol Buffers which works in a simliar way to Thrift, except it only does data type definition. How is it different from Thirft? Google has the following to say about that:

How do protocol buffers differ from ASN.1, COM, CORBA, Thrift, etc?

We think all of these systems have strengths and weaknesses. Google relies on protocol buffers internally and they are a vital component of our success, but that doesn’t mean they are the ideal solution for every problem. You should evaluate each alternative in the context of your own project.

It is worth noting, though, that several of these technologies define both an interchange format and an RPC (remote procedure call) protocol. Protocol buffers are just an interchange format. They could easily be used for RPC – and, indeed, they do have limited support for defining RPC services – but they are not tied to any one RPC implementation or protocol.

There’s been a few JavaScript implementations of Protocol Buffers floating around but none of them are as complete and polished as the protocol-buffers (GitHub: mafintosh/protocol-buffers, License: MIT) by Mathias Buus. Lets check it out!

 

1
npm install protocol-buffers

Usage

A simple definition for a Garage/Vehicle type of scenario might look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enum VehicleType {
  SEDAN = 0;
  COUPE = 1;
  VAN = 2;
}
message Vehicle {
  required int32 price = 0;
  required string make = null;
  optional VehicleType type;
}
message Garage {
  repeated Vehicle vehicles;
}

As you can see, the syntax is very similiar to C or JavaScript and is pretty self explanatory. G Lets make use of it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var protobuf = require('protocol-buffers/require');
var schema = protobuf('schema.proto');
var vehicle = {
  price: 120000,
  make: 'Cadillac',
  type: schema.VehicleType.COUPE
};
var garage = {
  vehicles: [vehicle]
};
console.log(JSON.stringify(garage, null, 2));
console.log(schema.Vehicle.encode(vehicle).toString('hex'));
console.log(schema.Garage.encode(garage).toString('hex'));

Example output

1
2
3
4
5
6
7
8
9
10
11
12
$ node protocol-buffer.js
{
  "vehicles": [
    {
      "price": 120000,
      "make""Cadillac",
      "type": 1
    }
  ]
}
00c0a9070208436164696c6c61630001
021000c0a9070208436164696c6c61630001

What Else?

Checkout the runnable example and github example repository.

Post navigation

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *