-
Notifications
You must be signed in to change notification settings - Fork 3
/
parser.js
37 lines (33 loc) · 1.15 KB
/
parser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const { Transform } = require('stream')
// Parser to split incoming serial data by a magic byte sequence
// followed by a length
class MagicByteLengthParser extends Transform {
constructor({ magicByte, ...args }) {
super(args)
this.delimiter = magicByte
this.buffer = Buffer.alloc(0)
this.nextLength = null
}
_transform(chunk, encoding, cb) {
let data = Buffer.concat([this.buffer, chunk])
let position
while ((position = data.indexOf(this.delimiter)) !== -1) {
// We need to at least be able to read the length byte
if (data.length < position + 2) break
const nextLength = data[position + 1]
// Make sure we have enough bytes to meet this length
const expectedEnd = position + nextLength + 2
if (data.length < expectedEnd) break
this.push(data.slice(position + 2, expectedEnd))
data = data.slice(expectedEnd)
}
this.buffer = data
cb()
}
_flush(cb) {
this.push(this.buffer)
this.buffer = Buffer.alloc(0)
cb()
}
}
module.exports = MagicByteLengthParser