-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
65 lines (55 loc) · 1.56 KB
/
index.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const { Transform } = require('readable-stream')
const capnp = require('capnp')
class ParseStream extends Transform {
constructor (schema, options = { emitEvery: 1, skip: 0 }) {
options.objectMode = true
super(options)
this.schema = schema
this.buffer = null
this.emitEvery = options.emitEvery
this.skip = options.skip
this.msgCounter = 0
}
_transform (chunk, encoding, callback) {
if (!this.buffer) {
this.buffer = chunk
} else {
this.buffer = Buffer.concat([this.buffer, chunk])
}
try {
let expectedSize = capnp.expectedSizeFromPrefix(this.buffer)
let data = null
while (this.buffer.length >= expectedSize) {
if (this.skip === (this.msgCounter % this.emitEvery)) {
data = capnp.parse(this.schema, this.buffer)
this.push(data)
}
this.buffer = this.buffer.slice(expectedSize)
expectedSize = capnp.expectedSizeFromPrefix(this.buffer)
this.msgCounter += 1
}
} catch (err) {
callback(err)
}
return callback()
}
}
class SerializeStream extends Transform {
constructor (schema, options = {}) {
options.objectMode = true
super(options)
this.options = options
this.schema = schema
}
_transform (chunk, encoding, callback) {
if (typeof chunk !== 'object') {
return callback(new Error(`Expected chunk must have been object, but received "${typeof chunk}"`))
}
this.push(capnp.serialize(this.schema, chunk))
return callback()
}
}
module.exports = {
ParseStream,
SerializeStream
}