-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathprotocol.js
38 lines (28 loc) · 811 Bytes
/
protocol.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
module.exports = (handleMessage) => {
process.stdin.on('readable', () => {
var input = []
var chunk
while (chunk = process.stdin.read()) {
input.push(chunk)
}
input = Buffer.concat(input)
var msgLen = input.readUInt32LE(0)
var dataLen = msgLen + 4
if (input.length >= dataLen) {
var content = input.slice(4, dataLen)
var json = JSON.parse(content.toString())
handleMessage(json)
}
})
function sendMessage (msg) {
var buffer = Buffer.from(JSON.stringify(msg))
var header = Buffer.alloc(4)
header.writeUInt32LE(buffer.length, 0)
var data = Buffer.concat([header, buffer])
process.stdout.write(data)
}
process.on('uncaughtException', (err) => {
sendMessage({error: err.toString()})
})
return sendMessage
}