fifo.js
A simple fifo buffer for node-buffers. Excellent for handling encapsulated binary data in a TCP/IP stream. I encountered many situations where I needed to decode an embedded packet structure from a socket stream.
Installation
As npm for Node.js:
$ npm install fifo-buffer
Example
Some console interaction:
> FIFO=require('./fifo.js')
[Function: FIFOBuffer]
> b = new FIFO()
FIFOBuffer {
buffer: <Buffer 00 00 00 00 00 00 00 00 00 ... >,
high: 1048576,
tail: 0,
head: 0 }
> b.enq(Buffer.from([1,2,3,4]))
true
> b.enq(Buffer.from([5,6,7,8]))
true
> b.deq(2)
<Buffer 01 02>
> b.deq(2)
<Buffer 03 04>
> b.deq(2)
<Buffer 05 06>
> b.deq(2)
<Buffer 07 08>
> b.deq(2)
null
> b.enq(Buffer.from([1,2,3,4]))
true
> b.peek(2)
<Buffer 01 02>
> b.peek(2)
<Buffer 01 02>
> b.peek(5)
null
> b.size
4
>
A sample interface to extract a packet within a TCP/IP stream. Assuming socket is configured to provide a buffer on "data". The encapsulated packet simply begins with a 4 byte header containing its length.
var FIFO = ;var fifo = ; // ... assuming socket setup and connected:socket;
API
FIFOBuffer()
Initializes a new empty FIFOBuffer
with the default capacity (1MByte).
FIFOBuffer(capacity)
Initializes a new empty FIFOBuffer
with the given capacity
.
FIFOBuffer#deq(n)
Dequeues the oldest n bytes of the FIFO buffer and returns a copy.
Returns null
when the buffer has less bytes available.
FIFOBuffer#enq(buffer)
Enqueues the buffer
at the end and returns true
when there was enough space.
When the buffer is full the method returns false
.
FIFOBuffer#peek(n)
Copies the oldest n bytes of the FIFO buffer. Does not change the state.
Returns null
when the buffer has less bytes available.
FIFOBuffer#size
Returns the current size of the FIFO.
Testing
As npm package:
$ npm test
Licence
ISC