Skip to content

Commit f7eb2f0

Browse files
authored
feat(parsers): ByteLength is now more efficient (#1402)
And better documented
1 parent dcd256d commit f7eb2f0

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

lib/parsers/byte-length.js

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,16 @@ const Transform = require('stream').Transform;
55
/**
66
* A transform stream that emits data as a buffer after a specific number of bytes are received.
77
* @extends Transform
8+
* @param {Object} options
9+
* @param {Number} options.length the number of bytes on each data event
810
* @example
9-
To use the `ByteLength` parser, provide the length of the number of bytes:
11+
To use the `ByteLength` parser:
1012
```js
1113
const SerialPort = require('serialport');
1214
const ByteLength = SerialPort.parsers.ByteLength
1315
const port = new SerialPort('/dev/tty-usbserial1');
1416
const parser = port.pipe(new ByteLength({length: 8}));
15-
parser.on('data', console.log);
17+
parser.on('data', console.log); // will have 8 bytes per data event
1618
```
1719
*/
1820
class ByteLengthParser extends Transform {
@@ -29,23 +31,28 @@ class ByteLengthParser extends Transform {
2931
}
3032

3133
this.length = options.length;
32-
this.buffer = Buffer.alloc(0);
34+
this.position = 0;
35+
this.buffer = Buffer.alloc(this.length);
3336
}
3437

3538
_transform(chunk, encoding, cb) {
36-
let data = Buffer.concat([this.buffer, chunk]);
37-
while (data.length >= this.length) {
38-
const out = data.slice(0, this.length);
39-
this.push(out);
40-
data = data.slice(this.length);
39+
let cursor = 0;
40+
while (cursor < chunk.length) {
41+
this.buffer[this.position] = chunk[cursor];
42+
cursor++;
43+
this.position++;
44+
if (this.position === this.length) {
45+
this.push(this.buffer);
46+
this.buffer = Buffer.alloc(this.length);
47+
this.position = 0;
48+
}
4149
}
42-
this.buffer = data;
4350
cb();
4451
}
4552

4653
_flush(cb) {
47-
this.push(this.buffer);
48-
this.buffer = Buffer.alloc(0);
54+
this.push(this.buffer.slice(0, this.position));
55+
this.buffer = Buffer.alloc(this.length);
4956
cb();
5057
}
5158
};

0 commit comments

Comments
 (0)