forked from iarna/iarna-toml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse-stream.js
80 lines (75 loc) · 1.59 KB
/
parse-stream.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict'
module.exports = parseStream
const stream = require('stream')
const TOMLParser = require('./lib/toml-parser.js')
function parseStream (stm) {
if (stm) {
return parseReadable(stm)
} else {
return parseTransform(stm)
}
}
function parseReadable (stm) {
const parser = new TOMLParser()
stm.setEncoding('utf8')
return new Promise((resolve, reject) => {
let readable
let ended = false
let errored = false
function finish () {
ended = true
if (readable) return
try {
resolve(parser.finish())
} catch (err) {
reject(err)
}
}
function error (err) {
errored = true
reject(err)
}
stm.once('end', finish)
stm.once('error', error)
readNext()
function readNext () {
readable = true
let data
while ((data = stm.read()) !== null) {
try {
parser.parse(data)
} catch (err) {
return error(err)
}
}
readable = false
/* istanbul ignore if */
if (ended) return finish()
/* istanbul ignore if */
if (errored) return
stm.once('readable', readNext)
}
})
}
function parseTransform () {
const parser = new TOMLParser()
return new stream.Transform({
objectMode: true,
transform (chunk, encoding, cb) {
try {
parser.parse(chunk.toString(encoding))
} catch (err) {
this.emit('error', err)
}
cb()
},
flush (cb) {
try {
this.push(parser.finish())
} catch (err) {
this.emit('error', err)
}
cb()
}
})
}