Binary Protocol
Easy, fast, writers and readers for implementing custom binary protocols in node.js.
Installation
Via npm:
npm install --save binary-protocol
Usage
Defining a protocol
var BinaryProtocol = ; var protocol = ; // define a type called 'Bytes', which is simply// a series of raw bytes prefixed by length.protocol; // define a type called `String`, which is encoded as a length// prefixed series of bytes.protocol;
Writing data
var writer = protocol; writer // op code // user name; // password var buffer = writerbuffer; someWritableStream;
Reading data
var reader = protocol; reader; console; // {opCode: 100, username: 'admin', password: 'password'}
Request / Response
You can also define aggregate commands which represent a request / response
protocol.define('Login', { write: function (data) { this .Int32BE(100) // op code .String(data.username) .String(data.password); }, read: function () { this .Int32BE('status') .tap(function (data) { if (data.status === 0) { return this.String('error'); } else { return this .String('nickname') .Int32BE('totalUnreadMessages'); } }); } });
var net = require('net'), client = net.createClient('localhost', 3030), commander = protocol.createCommander(client);
var details = { username: 'admin', password: 'password' };
commander.Login(details).then(function (response) { console.log(response); });
Running the tests
First, npm install
, then npm test
. Code coverage generated with npm run coverage
.
License
MIT, see LICENSE.md.