diff --git a/README.md b/README.md
index cb0a2a7..aacf439 100644
--- a/README.md
+++ b/README.md
@@ -507,57 +507,58 @@ The `close` event's callback is called with no arguments when the port is closed
#### `SerialPort.parsers` : object
-Parsers will process incoming data in a variety of ways and are meant to be passed to a port during construction.
+The default Parsers are [Transform streams](https://nodejs.org/api/stream.html#stream_class_stream_transform) that will parse data in a variety of ways and can be used to process incoming data.
+
+ To use any of the parsers you need to create them and then pipe the serialport to the parser. Be sure not to write to the parser but to the SerialPort object.
**Kind**: static property of [SerialPort](#exp_module_serialport--SerialPort)
**Properties**
| Name | Type | Description |
| --- | --- | --- |
-| raw | function | emits a raw buffer as a data event as it's received. This is the default parser. |
-| readline | function | returns a function that emits a string as a data event after a newline delimiter is received. |
-| byteLength | function | returns a function that emits a data event as a buffer after a specific number of bytes are received. |
-| byteDelimiter | function | returns a function that emits a data event each time a byte sequence (an array of bytes) is received. |
+| ByteLength | Class | is a transform stream that emits data each time a byte sequence is received. |
+| Delimiter | Class | is a transform stream that emits data as a buffer after a specific number of bytes are received. |
+| ReadLine | Class | is a transform stream that emits data after a newline delimiter is received. |
**Example**
-To use the readline parser, you must provide a delimiter as such:
-
```js
var SerialPort = require('serialport');
+var ReadLine = SerialPort.parsers.ReadLine;
+var port = new SerialPort('/dev/tty-usbserial1');
+var parser = new ReadLine();
+port.pipe(parser);
+parser.on('data', console.log);
+port.write('ROBOT PLEASE RESPOND\n');
-var port = new SerialPort('/dev/tty-usbserial1', {
- parser: SerialPort.parsers.readline('\n')
-});
+// creating the parser and piping can be shortened to
+var parser = port.pipe(new ReadLine());
```
-To use the raw parser don't specify any parser, however if you really want to you can:
-
+To use the byte length parser, you must provide the length of the number of bytes:
```js
var SerialPort = require('serialport');
-
-var port = new SerialPort('/dev/tty-usbserial1', {
- parser: SerialPort.parsers.raw
-});
+var ByteLength = SerialPort.parsers.ByteLength
+var port = new SerialPort('/dev/tty-usbserial1');
+var parser = port.pipe(new ByteLength({length: 8}));
+parser.on('data', console.log);
```
-Note that the raw parser does not guarantee that all data it receives will come in a single event.
-
-To use the byte sequence parser, you must provide a delimiter as an array of bytes:
+To use the Delimiter parser you must specify, you must provide a delimiter as a string, buffer, or an array of bytes:
```js
var SerialPort = require('serialport');
-
-var port = new SerialPort('/dev/tty-usbserial1', {
- parser: SerialPort.parsers.byteDelimiter([10,13])
-});
+var Delimiter = SerialPort.parsers.Delimiter;
+var port = new SerialPort('/dev/tty-usbserial1');
+var parser = port.pipe(new Delimiter({delimiter: new Buffer('EOL')}));
+parser.on('data', console.log);
```
-To use the byte length parser, you must provide a delimiter as a length in bytes:
+To use the ReadLine parser, you may provide a delimiter (defaults to '\n')
```js
var SerialPort = require('serialport');
-
-var port = new SerialPort('/dev/tty-usbserial1', {
- parser: SerialPort.parsers.byteLength(5)
-});
+var ReadLine = SerialPort.parsers.ReadLine;
+var port = new SerialPort('/dev/tty-usbserial1');
+var parser = port.pipe(ReadLine({delimiter: '\r\n'}));
+parser.on('data', console.log);
```
-
@@ -634,7 +635,6 @@ A callback called with an error or null.
| xoff | boolean | false | flow control setting |
| xany | boolean | false | flow control setting |
| bufferSize | number | 65536 | Size of read buffer |
-| parser | function | Parsers.raw | The parser to transform read data, defaults to the `raw` parser that emits data as it's received. |
| platformOptions | object | | sets platform specific options |
| platformOptions.vmin | number | 1 | see [`man termios`](http://linux.die.net/man/3/termios) |
| platformOptions.vtime | number | 0 | see [`man termios`](http://linux.die.net/man/3/termios) |
diff --git a/lib/parser-byte-length.js b/lib/parser-byte-length.js
new file mode 100644
index 0000000..ae5a95e
--- /dev/null
+++ b/lib/parser-byte-length.js
@@ -0,0 +1,45 @@
+'use strict';
+var Transform = require('readable-stream').Transform;
+var inherits = require('inherits');
+
+function ByteLengthParser(options) {
+ if (!(this instanceof ByteLengthParser)) {
+ return new ByteLengthParser(options);
+ }
+ Transform.call(this, options);
+
+ options = options || {};
+
+ if (typeof options.length !== 'number') {
+ throw new TypeError('length is not a number');
+ }
+
+ if (options.length < 1) {
+ throw new TypeError('length is not greater than 0');
+ }
+
+ this.length = options.length;
+ this.buffer = new Buffer(0);
+}
+
+inherits(ByteLengthParser, Transform);
+
+ByteLengthParser.prototype._transform = function(chunk, encoding, cb) {
+ var data = Buffer.concat([this.buffer, chunk]);
+ while (data.length >= this.length) {
+ var out = data.slice(0, this.length);
+ this.push(out);
+ data = data.slice(this.length);
+ }
+ this.buffer = data;
+ cb();
+};
+
+ByteLengthParser.prototype._flush = function(cb) {
+ this.push(this.buffer);
+ this.buffer = new Buffer(0);
+ cb();
+};
+
+
+module.exports = ByteLengthParser;
diff --git a/lib/parser-delimiter.js b/lib/parser-delimiter.js
new file mode 100644
index 0000000..94d0db6
--- /dev/null
+++ b/lib/parser-delimiter.js
@@ -0,0 +1,53 @@
+'use strict';
+var Transform = require('readable-stream').Transform;
+var inherits = require('inherits');
+var bindexOf;
+
+if (typeof Buffer.prototype.indexOf === 'function') {
+ bindexOf = function(buff, search, offset, encoding) {
+ return buff.indexOf(search, offset, encoding);
+ };
+} else {
+ bindexOf = require('buffer-indexof');
+}
+
+function DelimiterParser(options) {
+ if (!(this instanceof DelimiterParser)) {
+ return new DelimiterParser(options);
+ }
+ Transform.call(this, options);
+
+ options = options || {};
+
+ if (options.delimiter === undefined) {
+ throw new TypeError('delimiter is not a bufferable object');
+ }
+
+ if (options.delimiter.length === 0) {
+ throw new TypeError('delimiter has a 0 or undefined length');
+ }
+
+ this.delimiter = new Buffer(options.delimiter);
+ this.buffer = new Buffer(0);
+}
+
+inherits(DelimiterParser, Transform);
+
+DelimiterParser.prototype._transform = function(chunk, encoding, cb) {
+ var data = Buffer.concat([this.buffer, chunk]);
+ var position;
+ while ((position = bindexOf(data, this.delimiter)) !== -1) {
+ this.push(data.slice(0, position));
+ data = data.slice(position + this.delimiter.length);
+ }
+ this.buffer = data;
+ cb();
+};
+
+DelimiterParser.prototype._flush = function(cb) {
+ this.push(this.buffer);
+ this.buffer = new Buffer(0);
+ cb();
+};
+
+module.exports = DelimiterParser;
diff --git a/lib/parser-read-line.js b/lib/parser-read-line.js
new file mode 100644
index 0000000..3b80118
--- /dev/null
+++ b/lib/parser-read-line.js
@@ -0,0 +1,24 @@
+'use strict';
+var DelimiterParser = require('./parser-delimiter');
+var inherits = require('inherits');
+
+function ReadLineParser(options) {
+ if (!(this instanceof ReadLineParser)) {
+ return new ReadLineParser(options);
+ }
+
+ options = options || {};
+
+ if (options.delimiter === undefined) {
+ options.delimiter = new Buffer('\n', 'utf8');
+ }
+
+ DelimiterParser.call(this, options);
+
+ var encoding = options.encoding || 'utf8';
+ this.delimiter = new Buffer(options.delimiter, encoding);
+ this.setEncoding(encoding);
+}
+
+inherits(ReadLineParser, DelimiterParser);
+module.exports = ReadLineParser;
diff --git a/lib/parsers.js b/lib/parsers.js
index 283dd6b..3993d83 100644
--- a/lib/parsers.js
+++ b/lib/parsers.js
@@ -1,73 +1,58 @@
'use strict';
-// Copyright 2011 Chris Williams
+/**
+ * The default Parsers are [Transform streams](https://nodejs.org/api/stream.html#stream_class_stream_transform) that will parse data in a variety of ways and can be used to process incoming data.
-function isEqual(arr1, arr2) {
- var isArray = Array.isArray;
- if (!isArray(arr1) || !isArray(arr2) || arr1.length !== arr2.length) {
- return false;
- }
- var l = arr1.length;
- for (var i = 0; i < l; i += 1) {
- if (arr1[i] !== arr2[i]) {
- return false;
- }
- }
- return true;
-}
+ To use any of the parsers you need to create them and then pipe the serialport to the parser. Be sure not to write to the parser but to the SerialPort object.
+ * @name module:serialport.parsers
+ * @type {object}
+ * @property {Class} [ByteLength] is a transform stream that emits data each time a byte sequence is received.
+ * @property {Class} [Delimiter] is a transform stream that emits data as a buffer after a specific number of bytes are received.
+ * @property {Class} [ReadLine] is a transform stream that emits data after a newline delimiter is received.
+ * @example
+```js
+var SerialPort = require('serialport');
+var ReadLine = SerialPort.parsers.ReadLine;
+var port = new SerialPort('/dev/tty-usbserial1');
+var parser = new ReadLine();
+port.pipe(parser);
+parser.on('data', console.log);
+port.write('ROBOT PLEASE RESPOND\n');
+
+// creating the parser and piping can be shortened to
+var parser = port.pipe(new ReadLine());
+```
+
+To use the byte length parser, you must provide the length of the number of bytes:
+```js
+var SerialPort = require('serialport');
+var ByteLength = SerialPort.parsers.ByteLength
+var port = new SerialPort('/dev/tty-usbserial1');
+var parser = port.pipe(new ByteLength({length: 8}));
+parser.on('data', console.log);
+```
+
+To use the Delimiter parser you must specify, you must provide a delimiter as a string, buffer, or an array of bytes:
+```js
+var SerialPort = require('serialport');
+var Delimiter = SerialPort.parsers.Delimiter;
+var port = new SerialPort('/dev/tty-usbserial1');
+var parser = port.pipe(new Delimiter({delimiter: new Buffer('EOL')}));
+parser.on('data', console.log);
+```
+
+To use the ReadLine parser, you may provide a delimiter (defaults to '\n')
+```js
+var SerialPort = require('serialport');
+var ReadLine = SerialPort.parsers.ReadLine;
+var port = new SerialPort('/dev/tty-usbserial1');
+var parser = port.pipe(ReadLine({delimiter: '\r\n'}));
+parser.on('data', console.log);
+```
+ */
module.exports = {
- raw: function(emitter, buffer) {
- emitter.emit('data', buffer);
- },
-
- // encoding: ascii utf8 utf16le ucs2 base64 binary hex
- // More: http://nodejs.org/api/buffer.html#buffer_buffer
- readline: function(delimiter, encoding) {
- if (typeof delimiter === 'undefined' || delimiter === null) { delimiter = '\r' }
- if (typeof encoding === 'undefined' || encoding === null) { encoding = 'utf8' }
- // Delimiter buffer saved in closure
- var data = '';
- return function(emitter, buffer) {
- // Collect data
- data += buffer.toString(encoding);
- // Split collected data by delimiter
- var parts = data.split(delimiter);
- data = parts.pop();
- parts.forEach(function(part) {
- emitter.emit('data', part);
- });
- };
- },
-
- // Emit a data event every `length` bytes
- byteLength: function(length) {
- var data = new Buffer(0);
- return function(emitter, buffer) {
- data = Buffer.concat([data, buffer]);
- while (data.length >= length) {
- var out = data.slice(0, length);
- data = data.slice(length);
- emitter.emit('data', out);
- }
- };
- },
-
- // Emit a data event each time a byte sequence (delimiter is an array of byte) is found
- // Sample usage : byteDelimiter([10, 13])
- byteDelimiter: function(delimiter) {
- if (!Array.isArray(delimiter)) {
- delimiter = [ delimiter ];
- }
- var buf = [];
- return function(emitter, buffer) {
- for (var i = 0; i < buffer.length; i++) {
- buf[buf.length] = buffer[i];
- if (isEqual(delimiter, buf.slice(-delimiter.length))) {
- emitter.emit('data', buf);
- buf = [];
- }
- }
- };
- }
+ ReadLine: require('./parser-read-line'),
+ Delimiter: require('./parser-delimiter'),
+ ByteLength: require('./parser-byte-length')
};
diff --git a/lib/serialport.js b/lib/serialport.js
index b5c36ee..e05b153 100644
--- a/lib/serialport.js
+++ b/lib/serialport.js
@@ -44,7 +44,6 @@ var defaultSettings = {
stopBits: 1,
bufferSize: 64 * 1024,
lock: true,
- parser: parsers.raw,
platformOptions: SerialPortBinding.platformOptions
};
@@ -75,7 +74,6 @@ var defaultSetFlags = {
* @property {boolean} [xoff=false] flow control setting
* @property {boolean} [xany=false] flow control setting
* @property {number} [bufferSize=65536] Size of read buffer
- * @property {function} [parser=Parsers.raw] The parser to transform read data, defaults to the `raw` parser that emits data as it's received.
* @property {object=} platformOptions sets platform specific options
* @property {number} [platformOptions.vmin=1] see [`man termios`](http://linux.die.net/man/3/termios)
* @property {number} [platformOptions.vtime=0] see [`man termios`](http://linux.die.net/man/3/termios)
@@ -156,7 +154,6 @@ function SerialPort(path, options, callback) {
});
settings.disconnectedCallback = this._disconnected.bind(this);
- settings.dataCallback = settings.parser.bind(this, this);
this.fd = null;
this.paused = true;
@@ -371,7 +368,7 @@ if (process.platform !== 'win32') {
};
SerialPort.prototype._emitData = function(data) {
- this.options.dataCallback(data);
+ this.emit('data', data);
};
@@ -529,12 +526,12 @@ SerialPort.prototype.flush = function(callback) {
return this._error(new Error('Port is not open'), callback);
}
- SerialPortBinding.flush(this.fd, function(err, result) {
+ SerialPortBinding.flush(this.fd, function(err) {
if (err) {
debug('SerialPortBinding.flush had an error', err);
return this._error(err, callback);
}
- if (callback) { callback.call(this, null, result) }
+ if (callback) { callback.call(this, null) }
}.bind(this));
};
@@ -567,57 +564,6 @@ SerialPort.prototype.drain = function(callback) {
}.bind(this));
};
-/**
- * Parsers will process incoming data in a variety of ways and are meant to be passed to a port during construction.
- * @type {object}
- * @property {function} [raw] emits a raw buffer as a data event as it's received. This is the default parser.
- * @property {function} [readline] returns a function that emits a string as a data event after a newline delimiter is received.
- * @property {function} [byteLength] returns a function that emits a data event as a buffer after a specific number of bytes are received.
- * @property {function} [byteDelimiter] returns a function that emits a data event each time a byte sequence (an array of bytes) is received.
- * @example
-To use the readline parser, you must provide a delimiter as such:
-
-```js
-var SerialPort = require('serialport');
-
-var port = new SerialPort('/dev/tty-usbserial1', {
- parser: SerialPort.parsers.readline('\n')
-});
-```
-
-To use the raw parser don't specify any parser, however if you really want to you can:
-
-```js
-var SerialPort = require('serialport');
-
-var port = new SerialPort('/dev/tty-usbserial1', {
- parser: SerialPort.parsers.raw
-});
-```
-
-Note that the raw parser does not guarantee that all data it receives will come in a single event.
-
-To use the byte sequence parser, you must provide a delimiter as an array of bytes:
-```js
-var SerialPort = require('serialport');
-
-var port = new SerialPort('/dev/tty-usbserial1', {
- parser: SerialPort.parsers.byteDelimiter([10,13])
-});
-```
-
-To use the byte length parser, you must provide a delimiter as a length in bytes:
-```js
-var SerialPort = require('serialport');
-
-var port = new SerialPort('/dev/tty-usbserial1', {
- parser: SerialPort.parsers.byteLength(5)
-});
-```
- */
-
-SerialPort.parsers = parsers;
-
/**
* This callback type is called `requestCallback` and is displayed as a global symbol.
*
@@ -669,5 +615,12 @@ Object.defineProperty(SerialPort, 'SerialPort', {
},
configurable: true
});
+SerialPort.parsers = {
+ ReadLine: require('./parser-read-line'),
+ Delimiter: require('./parser-delimiter'),
+ ByteLength: require('./parser-byte-length')
+};
+
+SerialPort.parsers = parsers;
module.exports = SerialPort;
diff --git a/package.json b/package.json
index 4640836..e1f3284 100644
--- a/package.json
+++ b/package.json
@@ -53,12 +53,15 @@
],
"dependencies": {
"bindings": "1.2.1",
+ "buffer-indexof": "^1.0.2",
"commander": "^2.9.0",
"debug": "^2.1.1",
+ "inherits": "^2.0.1",
"lie": "^3.1.0",
"nan": "^2.3.5",
"node-pre-gyp": "^0.6.26",
- "object.assign": "^4.0.3"
+ "object.assign": "^4.0.3",
+ "readable-stream": "^2.1.4"
},
"devDependencies": {
"chai": "^3.5.0",
diff --git a/test/parser-byte-length.js b/test/parser-byte-length.js
new file mode 100644
index 0000000..ad24518
--- /dev/null
+++ b/test/parser-byte-length.js
@@ -0,0 +1,53 @@
+'use strict';
+
+var assert = require('chai').assert;
+var sinon = require('sinon');
+
+var ByteLengthParser = require('../lib/parser-byte-length');
+
+describe('ByteLengthParser', function() {
+ it('emits data events every 8 bytes', function() {
+ var data = new Buffer('Robots are so freaking cool!');
+ var spy = sinon.spy();
+ var parser = new ByteLengthParser({length: 8});
+ parser.on('data', spy);
+ parser.write(data);
+ assert.equal(spy.callCount, 3);
+ assert.deepEqual(spy.getCall(0).args[0], new Buffer('Robots a'));
+ assert.deepEqual(spy.getCall(1).args[0], new Buffer('re so fr'));
+ assert.deepEqual(spy.getCall(2).args[0], new Buffer('eaking c'));
+ });
+
+ it('throws when not provided with a length', function() {
+ assert.throws(function() {
+ new ByteLengthParser({});
+ });
+ });
+
+ it('throws when length is zero', function() {
+ assert.throws(function() {
+ new ByteLengthParser({
+ length: 0
+ });
+ });
+ });
+
+ it('throws when called with a non numeric length', function() {
+ assert.throws(function() {
+ new ByteLengthParser({
+ length: 'foop'
+ });
+ });
+ });
+
+ it('continues looking for bytes in additional writes', function() {
+ var parser = new ByteLengthParser({length: 4});
+ var spy = sinon.spy();
+ parser.on('data', spy);
+ parser.write(new Buffer('ab'));
+ parser.write(new Buffer('cd'));
+ assert.equal(spy.callCount, 1);
+ assert.deepEqual(spy.getCall(0).args[0], new Buffer('abcd'));
+ });
+});
+
diff --git a/test/parser-delimiter.js b/test/parser-delimiter.js
new file mode 100644
index 0000000..368903a
--- /dev/null
+++ b/test/parser-delimiter.js
@@ -0,0 +1,116 @@
+'use strict';
+
+var assert = require('chai').assert;
+var sinon = require('sinon');
+
+var DelimiterParser = require('../lib/parser-delimiter');
+
+describe('DelimiterParser', function() {
+ it('transforms data to strings split on a delimiter', function() {
+ var spy = sinon.spy();
+ var parser = new DelimiterParser({
+ delimiter: new Buffer('\n')
+ });
+ parser.on('data', spy);
+ parser.write(new Buffer('I love robots\nEach '));
+ parser.write(new Buffer('and Every One\n'));
+ parser.write(new Buffer('even you!'));
+
+ assert.deepEqual(spy.getCall(0).args[0], new Buffer('I love robots'));
+ assert.deepEqual(spy.getCall(1).args[0], new Buffer('Each and Every One'));
+ assert(spy.calledTwice);
+ parser.end();
+ assert.deepEqual(spy.getCall(2).args[0], new Buffer('even you!'));
+ assert(spy.calledThrice);
+ });
+
+ it('throws when not provided with a delimiter', function() {
+ assert.throws(function() {
+ new DelimiterParser({});
+ });
+ });
+
+ it('throws when called with a 0 length delimiter', function() {
+ assert.throws(function() {
+ new DelimiterParser({
+ delimiter: new Buffer(0)
+ });
+ });
+
+ assert.throws(function() {
+ new DelimiterParser({
+ delimiter: ''
+ });
+ });
+
+ assert.throws(function() {
+ new DelimiterParser({
+ delimiter: []
+ });
+ });
+ });
+
+ it('allows setting of the delimiter with a string', function() {
+ new DelimiterParser({delimiter: 'string'});
+ });
+
+ it('allows setting of the delimiter with a buffer', function() {
+ new DelimiterParser({delimiter: new Buffer([1])});
+ });
+
+ it('allows setting of the delimiter with an array of bytes', function() {
+ new DelimiterParser({delimiter: [1]});
+ });
+
+ it('emits data events every time it meets 00x 00x', function() {
+ var data = new Buffer('This could be\0\0binary data\0\0sent from a Moteino\0\0');
+ var parser = new DelimiterParser({delimiter: [0, 0]});
+ var spy = sinon.spy();
+ parser.on('data', spy);
+ parser.write(data);
+ assert.equal(spy.callCount, 3);
+ assert.deepEqual(spy.getCall(0).args[0], new Buffer('This could be'));
+ assert.deepEqual(spy.getCall(1).args[0], new Buffer('binary data'));
+ assert.deepEqual(spy.getCall(2).args[0], new Buffer('sent from a Moteino'));
+ });
+
+ it('accepts single byte delimiter', function() {
+ var data = new Buffer('This could be\0binary data\0sent from a Moteino\0');
+ var parser = new DelimiterParser({delimiter: [0]});
+ var spy = sinon.spy();
+ parser.on('data', spy);
+ parser.write(data);
+ assert.equal(spy.callCount, 3);
+ });
+
+ it('Works when buffer starts with delimiter', function() {
+ var data = new Buffer('\0Hello\0World\0');
+ var parser = new DelimiterParser({delimiter: new Buffer([0])});
+ var spy = sinon.spy();
+ parser.on('data', spy);
+ parser.write(data);
+ assert.equal(spy.callCount, 2);
+ });
+
+ it('should only emit if delimiters are strictly in row', function() {
+ var data = new Buffer('\0Hello\u0001World\0\0\u0001');
+ var parser = new DelimiterParser({delimiter: [0, 1]});
+ var spy = sinon.spy();
+ parser.on('data', spy);
+ parser.write(data);
+ assert.equal(spy.callCount, 1);
+ });
+
+ it('continues looking for delimiters in the next buffers', function() {
+ var parser = new DelimiterParser({delimiter: [0, 0]});
+ var spy = sinon.spy();
+ parser.on('data', spy);
+ parser.write(new Buffer('This could be\0\0binary '));
+ parser.write(new Buffer('data\0\0sent from a Moteino\0\0'));
+ assert.equal(spy.callCount, 3);
+ assert.deepEqual(spy.getCall(0).args[0], new Buffer('This could be'));
+ assert.deepEqual(spy.getCall(1).args[0], new Buffer('binary data'));
+ assert.deepEqual(spy.getCall(2).args[0], new Buffer('sent from a Moteino'));
+ });
+});
+
diff --git a/test/parser-read-line.js b/test/parser-read-line.js
new file mode 100644
index 0000000..725d2b7
--- /dev/null
+++ b/test/parser-read-line.js
@@ -0,0 +1,114 @@
+'use strict';
+
+var assert = require('chai').assert;
+var sinon = require('sinon');
+
+var ReadLineParser = require('../lib/parser-read-line');
+
+describe('ReadLineParser', function() {
+ it('transforms data to strings split on a delimiter', function() {
+ var spy = sinon.spy();
+ var parser = new ReadLineParser();
+ parser.on('data', spy);
+ parser.write(new Buffer('I love robots\nEach '));
+ parser.write(new Buffer('and Every One\n'));
+ parser.write(new Buffer('even you!'));
+ assert(spy.calledWith('I love robots'));
+ assert(spy.calledWith('Each and Every One'));
+ assert(spy.calledTwice);
+ parser.end();
+ assert(spy.calledWith('even you!'));
+ assert(spy.calledThrice);
+ });
+
+ it('allows setting of the delimiter with a string', function() {
+ var spy = sinon.spy();
+ var parser = new ReadLineParser({delimiter: 'a'});
+ parser.on('data', spy);
+ parser.write(new Buffer('how are youa'));
+ assert(spy.calledWith('how '));
+ assert(spy.calledWith('re you'));
+ });
+
+ it('allows setting of the delimiter with a buffer', function() {
+ var spy = sinon.spy();
+ var parser = new ReadLineParser({delimiter: new Buffer('a')});
+ parser.on('data', spy);
+ parser.write(new Buffer('how are youa'));
+ assert(spy.calledWith('how '));
+ assert(spy.calledWith('re you'));
+ });
+
+ it('allows setting of the delimiter with an array of bytes', function() {
+ var spy = sinon.spy();
+ var parser = new ReadLineParser({delimiter: [97]});
+ parser.on('data', spy);
+ parser.write(new Buffer('how are youa'));
+ assert(spy.calledWith('how '));
+ assert(spy.calledWith('re you'));
+ });
+
+ it('allows setting of encoding', function() {
+ var spy = sinon.spy();
+ var parser = new ReadLineParser({
+ encoding: 'hex'
+ });
+ parser.on('data', spy);
+ parser.write(new Buffer('a\nb\n'));
+ assert.equal(spy.getCall(0).args[0], '61');
+ assert.equal(spy.getCall(1).args[0], '62');
+ });
+
+ it('encoding should be reflected in a string delimiter', function() {
+ var spy = sinon.spy();
+ var parser = new ReadLineParser({
+ delimiter: 'FF',
+ encoding: 'hex'
+ });
+ parser.on('data', spy);
+ parser.write(new Buffer([0, 255, 1, 255]));
+ assert.equal(spy.getCall(0).args[0], '00');
+ assert.equal(spy.getCall(1).args[0], '01');
+ });
+
+ it('throws when called with a 0 length delimiter', function() {
+ assert.throws(function() {
+ new ReadLineParser({
+ delimiter: new Buffer(0)
+ });
+ });
+
+ assert.throws(function() {
+ new ReadLineParser({
+ delimiter: ''
+ });
+ });
+
+ assert.throws(function() {
+ new ReadLineParser({
+ delimiter: []
+ });
+ });
+ });
+
+ it('allows setting of the delimiter with a string', function() {
+ new ReadLineParser({delimiter: 'string'});
+ });
+
+ it('allows setting of the delimiter with a buffer', function() {
+ new ReadLineParser({delimiter: new Buffer([1])});
+ });
+
+ it('allows setting of the delimiter with an array of bytes', function() {
+ new ReadLineParser({delimiter: [1]});
+ });
+
+ it('doesn\'t emits empty data events', function() {
+ var spy = sinon.spy();
+ var parser = new ReadLineParser({delimiter: 'a'});
+ parser.on('data', spy);
+ parser.write(new Buffer('aFa'));
+ assert(spy.calledOnce);
+ assert(spy.calledWith('F'));
+ });
+});
diff --git a/test/parsers.js b/test/parsers.js
deleted file mode 100644
index 5864276..0000000
--- a/test/parsers.js
+++ /dev/null
@@ -1,97 +0,0 @@
-'use strict';
-
-var assert = require('chai').assert;
-var sinon = require('sinon');
-
-var parsers = require('../lib/parsers');
-
-describe('parsers', function() {
- describe('#raw', function() {
- it('emits data exactly as it\'s written', function() {
- var data = new Buffer('BOGUS');
- var spy = sinon.spy();
- parsers.raw({ emit: spy }, data);
- assert.deepEqual(spy.getCall(0).args[1], new Buffer('BOGUS'));
- });
- });
-
- describe('#readline', function() {
- it('emits data events split on a delimiter', function() {
- var data = new Buffer('I love robots\rEach and Every One\r');
- var spy = sinon.spy();
- var parser = parsers.readline();
- parser({ emit: spy }, data);
- assert(spy.calledWith('data', 'I love robots'));
- assert(spy.calledWith('data', 'Each and Every One'));
- });
- });
-
- describe('#byteLength', function() {
- it('emits data events every 8 bytes', function() {
- var data = new Buffer('Robots are so freaking cool!');
- var spy = sinon.spy();
- var parser = parsers.byteLength(8);
- parser({ emit: spy }, data);
- assert.equal(spy.callCount, 3);
- assert.deepEqual(spy.getCall(0).args[1], new Buffer('Robots a'));
- assert.deepEqual(spy.getCall(1).args[1], new Buffer('re so fr'));
- assert.deepEqual(spy.getCall(2).args[1], new Buffer('eaking c'));
- });
- });
-
- describe('#rawdelimiter', function() {
- it('emits data events every time it meets 00x 00x', function() {
- var data = new Buffer('This could be\0\0binary data\0\0sent from a Moteino\0\0');
- var parser = parsers.byteDelimiter([0, 0]);
- var spy = sinon.spy();
- parser({ emit: spy }, data);
- assert.equal(spy.callCount, 3);
- assert.equal(spy.getCall(0).args[1].length, 15);
- assert.deepEqual(new Buffer(spy.getCall(0).args[1]), (new Buffer('This could be\0\0')));
- assert.equal(spy.getCall(1).args[1].length, 13);
- assert.deepEqual(new Buffer(spy.getCall(1).args[1]), (new Buffer('binary data\0\0')));
- assert.equal(spy.getCall(2).args[1].length, 21);
- assert.deepEqual(new Buffer(spy.getCall(2).args[1]), (new Buffer('sent from a Moteino\0\0')));
- });
-
- it('accepts single byte delimiter', function() {
- var data = new Buffer('This could be\0binary data\0sent from a Moteino\0');
- var parser = parsers.byteDelimiter(0);
- var spy = sinon.spy();
- parser({ emit: spy }, data);
- assert.equal(spy.callCount, 3);
- });
-
- it('Works when buffer starts with delimiter', function() {
- var data = new Buffer('\0Hello\0World\0');
- var parser = parsers.byteDelimiter(0);
- var spy = sinon.spy();
- parser({ emit: spy }, data);
- assert.equal(spy.callCount, 3);
- });
-
- it('should only emit if delimiters are strictly in row', function() {
- var data = new Buffer('\0Hello\u0001World\0\0\u0001');
- var parser = parsers.byteDelimiter([0, 1]);
- var spy = sinon.spy();
- parser({ emit: spy }, data);
- assert.equal(spy.callCount, 1);
- });
-
- it('continues looking for delimiters in the next buffers', function() {
- var data1 = new Buffer('This could be\0\0binary ');
- var data2 = new Buffer('data\0\0sent from a Moteino\0\0');
- var parser = parsers.byteDelimiter([0, 0]);
- var spy = sinon.spy();
- parser({ emit: spy }, data1);
- parser({ emit: spy }, data2);
- assert.equal(spy.callCount, 3);
- assert.equal(spy.getCall(0).args[1].length, 15);
- assert.deepEqual(new Buffer(spy.getCall(0).args[1]), (new Buffer('This could be\0\0')));
- assert.equal(spy.getCall(1).args[1].length, 13);
- assert.deepEqual(new Buffer(spy.getCall(1).args[1]), (new Buffer('binary data\0\0')));
- assert.equal(spy.getCall(2).args[1].length, 21);
- assert.deepEqual(new Buffer(spy.getCall(2).args[1]), (new Buffer('sent from a Moteino\0\0')));
- });
- });
-});