-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
62 lines (47 loc) · 1.18 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
import { EventEmitter } from 'events'
class Pipe extends EventEmitter {
constructor (opts) {
super()
this.json = opts.json === true
if (!opts.json) {
process.stdin.on('data', data => {
this.emit('data', data)
})
return
}
let buf = ''
const parse = msg => {
try {
const json = JSON.parse(msg)
this.emit('data', json)
} catch (err) {
this.emit('warning', err)
}
}
process.stdin.on('data', data => {
const messages = data.split('\n')
if (messages.length === 1) {
buf += data
return
}
parse(buf + messages[0])
for (let i = 1; i < messages.length - 1; i++) {
parse(messages[i])
}
buf = messages[messages.length - 1]
})
process.stdin.setEncoding('utf8')
process.stdin.resume()
}
async write (data) {
if (data.constructor.name === 'Message') {
const str = data.toString()
return new Promise(resolve => process.stdout.write(str, resolve))
}
if (!this.json) {
return new Promise(resolve => process.stdout.write(data, resolve))
}
process.stdout.write(data)
}
}
export { Pipe }