binary-protocol 13

Easy, fast, writers and readers for implementing custom binary protocols in node.js.

codemix/binary-protocol

Written in JavaScript by 1 contributor

Contribute

Need Support?


we offer maintenance, support and development services for all our open source projects.

Contact Us

Binary Protocol

Build Status

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 = require('binary-protocol');

var protocol = new BinaryProtocol();

// define a type called 'Bytes', which is simply
// a series of raw bytes prefixed by length.
protocol.define('Bytes', {
  read: function (propertyName) {
    this
    .pushStack({length: null, value: null}) // allocate a new object to read the data into.
    .Int32BE('length') // read a 32 bit integer into the `length` property.
    .tap(function (data) {
      if (data.length === -1) {
        // if the length is -1, then there are no bytes and the value is null.
        data.value = null;
        return;
      }
      this.raw('value', data.length); // read N bytes into a property called `value`
    })
    .popStack(propertyName, function (data) {
      // pop the interim value off the stack and insert the real value into `propertyName`
      return data.value;
    });
  },
  write: function (value) {
    if (value === null) {
      this.Int32BE(-1); // a length of -1 indicates a null value.
    }
    else {
      // value is a buffer
      this
      .Int32BE(value.length) // write the buffer length
      .raw(value); // write the raw buffer
    }
  }
});

// define a type called `String`, which is encoded as a length
// prefixed series of bytes.
protocol.define('String', {
  read: function (propertyName) {
    this
    .Bytes(propertyName) // read `Bytes` into the property name.
    .collect(function (data) {
      // collect the final data to return
      if (data[propertyName] !== null) {
        data[propertyName] = data[propertyName].toString('utf8');
      }
      return data;
    });
  },
  write: function (value) {
    this.Bytes(new Buffer(value, 'utf8'));
  }
});

Writing data


var writer = protocol.createWriter();

writer
.Int32BE(100) // op code
.String('admin') // user name
.String('password'); // password

var buffer = writer.buffer;

someWritableStream.write(buffer);

Reading data

var reader = protocol.createReader(buffer);

reader
.Int32BE('opCode')
.String('username')
.String('password');

console.log(reader.next()); // {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.





44 other JavaScript projects


fast.jsJavaScript 2930

Faster user-land reimplementations for several common builtin native JavaScript functions.

babel-plugin-typecheckJavaScript 823

Static and runtime type checking for JavaScript in the form of a Babel plugin.

babel-plugin-closure-eliminationJavaScript 223

A Babel plugin which eliminates closures from your JavaScript wherever possible.

orientoJavaScript 212

Former official node.js driver for OrientDB. Fast, lightweight, uses the binary protocol. Now deprecated.

babel-plugin-macrosJavaScript 184

Hygienic, non-syntactic macros for JavaScript via a Babel plugin.

htmlingJavaScript 167

Polymer / HTML5 templating syntax for node.js

babel-plugin-contractsJavaScript 128

Design by Contract for JavaScript via a Babel plugin.

YiiBlocksJavaScript 70

A set of building blocks that provide common functions for Yii web applications

contractualJavaScript 52

Unobtrusive, backwards compatible, syntactic sugar for Design by contract in JavaScript.

gitignore-parserJavaScript 34

A simple .gitignore parser for node.js

modelingJavaScript 14

Fast and flexible data models for node.js and the browser.

YiiJSJavaScript 11

A port of the Yii PHP framework to JavaScript

url-routeJavaScript 10

Web component providing URL routing

validatingJavaScript 10

Quick and easy validators for node.js and the browser.

babel-plugin-traceJavaScript 6

This is a Babel plugin which adds a straightforward, declarative syntax for adding debug logging to JavaScript applications.

mallocJavaScript 6

Simple malloc() & free() implementation for node.js, built on top of array buffers.

geonames-importerJavaScript 6

Imports geonames data into elasticsearch

dispatchingJavaScript 5

Tiny routing / dispatch library for node and the browser.

atomicbuffersJavaScript 5

Atomic `readInt32()`, `writeInt32()`, `readUInt32()` and `writeUInt32()` for node.js buffers.

castingJavaScript 5

Tiny type casting library for node.js and the browser.

classingJavaScript 5

Fluent classes for node.js and the browser.

mimingJavaScript 3

Processing and formatting for various mime types.

bootstrap-tooltipJavaScript 1

Twitter Bootstrap Tooltip plugin packaged for component.js instead of bower

oriento-query-builderJavaScript 1

A standalone query builder for OrientDB, designed for node.js/io.js and the browser.

bootstrap-transitionJavaScript 1

Twitter Bootstrap Transition plugin packaged for component.js instead of bower

obligationsJavaScript 1

Tiny JavaScript library for preconditions and postconditions, intended for use with Contractual.

bootstrap-buttonJavaScript

Twitter Bootstrap Button plugin packaged for component.js instead of bower

bootstrap-popoverJavaScript

Twitter Bootstrap Popover plugin packaged for component.js instead of bower

bootstrap-scrollspyJavaScript

Twitter Bootstrap Scrollspy plugin packaged for component.js instead of bower

bootstrap-dropdownJavaScript

Twitter Bootstrap Dropdown plugin packaged for component.js instead of bower

bootstrap-tabJavaScript

Twitter Bootstrap Tab plugin packaged for component.js instead of bower

bootstrap-carouselJavaScript

Twitter Bootstrap Carousel plugin packaged for component.js instead of bower

webrtc-playgroundJavaScript

WebRTC sample code. For testing purposes only.

flex-basicJavaScript

A basic Flex App setup for video broadcasting

cover.jsJavaScript

JQuery plugin for covering/uncovering DOM elements

bootstrap-modalJavaScript

Twitter Bootstrap Modal plugin packaged for component.js instead of bower

bootstrap-alertJavaScript

Twitter Bootstrap Alert plugin packaged for component.js instead of bower

bootstrap-affixJavaScript

Twitter Bootstrap Affix plugin packaged for component.js instead of bower

ProductManagerJavaScript

A Sample CRUD application structured by Backbone js and backed by a node restfull api.

bootstrap-collapseJavaScript

Twitter Bootstrap Collapse plugin packaged for component.js instead of bower

bootstrap-componentJavaScript

Twitter Bootstrap packaged for component.js instead of bower

bootstrap-typeaheadJavaScript

Twitter Bootstrap Typeahead plugin packaged for component.js instead of bower

elevatorJavaScript

http://samsonradu.github.io/elevator/

tabinetJavaScript

A popular romanian card game