wuhkuh / protocol

Protocol generator / parser for Node.JS
MIT License
3 stars 3 forks source link

Protocols for Node.JS Build Status Greenkeeper badge

Create and edit network protocols the easy way.

No more bitwise logic - give it a template and let it do the work for you.

Installation

npm install protocol --save

Example

const Protocol = require('protocol')

const myProtocol = new Protocol({
  header: [{
    firstBit: { bitLength: 1 },
    secondBit: { bitLength: 1 }
  }],
  payloadLength: { bitLength: 4 },
  payload: { byteLength: 'payloadLength', encoding: 'utf8' } 
})

/* 
 * 0x90 is hex for '1001 0000'
 * firstBit: 1, secondBit: 0, payloadLength: 4 (bitwise 0100)
 * payload: 'abcd' (0x61 to 0x64)
 */
myProtocol.parse(Buffer.from([0x90, 0x61, 0x62, 0x63, 0x64]))

/*
 * '0 1 0010 00' to hex -> 0x48
 * 'bd' -> 0x62, 0x64
 * result: Buffer <0x48, 0x62, 0x64>
 */
myProtocol.generate({
  header: {
    firstBit: 0,
    secondBit: 1
  },
  payloadLength: 2, // this has to be set explicitly!
  payload: 'bd'
})

View the API or the example folder in this project's repository for a closer look.

Good practice:
Create a protocol in a separate file and share it between clients.

API


Protocol(schema)

Protocol is the exposed class. Create it by using new Protocol(schema).
The schema parameter is an object with the following notation:

const schema = {
  header: [{
    firstBit: { bitLength: 1 },
    secondBit: { bitLength: 1 }
  }],
  payloadLength: { bitLength: 4 },
  payload: { byteLength: 'payloadLength' }
}

Protocols are read in top-to-bottom order, with the input in Big Endian (network order as
defined in RFC 1700). This means that a Buffer will be parsed and generated from left to right.

The current supported options are:


Protocol.generate(object)

This method generates a Buffer from an Object. It starts with dictionary translation and
type handling, followed by concatenation and outputting a single Buffer.

If there is no encoding given during generation of a Buffer, it uses UTF-8.
If the input already contains a value of type Buffer, it will retain this Buffer.
When a length is variable and points to key x, x does not automatically get a value assigned.
This has to be set explicitly!


Protocol.parse(buffer)

This method generates an Object from a Buffer. It splits the individual bits and bytes,
followed by type handling and dictionary translation.

If there is no encoding given during parsing of a Buffer, it will retain this Buffer.

Supported Node versions

Version Supported until
Node v7 2017-06-01
Node v8 2019-12-31

License

MIT