@@ -5,14 +5,16 @@ const Transform = require('stream').Transform;
5
5
/**
6
6
* A transform stream that emits data as a buffer after a specific number of bytes are received.
7
7
* @extends Transform
8
+ * @param {Object } options
9
+ * @param {Number } options.length the number of bytes on each data event
8
10
* @example
9
- To use the `ByteLength` parser, provide the length of the number of bytes :
11
+ To use the `ByteLength` parser:
10
12
```js
11
13
const SerialPort = require('serialport');
12
14
const ByteLength = SerialPort.parsers.ByteLength
13
15
const port = new SerialPort('/dev/tty-usbserial1');
14
16
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
16
18
```
17
19
*/
18
20
class ByteLengthParser extends Transform {
@@ -29,23 +31,28 @@ class ByteLengthParser extends Transform {
29
31
}
30
32
31
33
this . length = options . length ;
32
- this . buffer = Buffer . alloc ( 0 ) ;
34
+ this . position = 0 ;
35
+ this . buffer = Buffer . alloc ( this . length ) ;
33
36
}
34
37
35
38
_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
+ }
41
49
}
42
- this . buffer = data ;
43
50
cb ( ) ;
44
51
}
45
52
46
53
_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 ) ;
49
56
cb ( ) ;
50
57
}
51
58
} ;
0 commit comments