-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (43 loc) · 982 Bytes
/
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
const { Transform } = require('stream')
const { encode, decode, END } = require('./slip')
function callback (cb) {
return (typeof cb === 'function') ? cb : () => {}
}
const proto = {
slice: function (chunk, start, end) {
this.push(chunk.slice(start, end))
},
add: function (data) {
this.push(data)
}
}
const encoder = () => {
let slice, add
const stream = new Transform({
transform: function (chunk, enc, cb) {
encode(chunk, slice, add)
cb()
},
flush: function (cb) {
this.push(END)
cb()
}
})
slice = proto.slice.bind(stream)
add = proto.add.bind(stream)
return stream
}
const decoder = (eof) => {
let slice, add
const stream = new Transform({
transform: function (chunk, enc, cb) {
decode(chunk, slice, add, eof)
cb()
}
})
slice = proto.slice.bind(stream)
add = proto.add.bind(stream)
eof = callback(eof).bind(stream)
return stream
}
module.exports = { encoder, decoder }