parser.js
2.58 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/* eslint-env mocha */
var jsonlines = require('../')
var assert = require('assert')
var concat = require('concat-stream')
describe('Parser', function () {
it('should handle simple jsonlines', function (done) {
var parser = jsonlines.parse()
var expected = [
{ a: 453345, b: 23423 },
{ c: 843222, d: 19534 },
{ e: 656564, f: 76521 }
]
parser.pipe(concat({ encoding: 'object' }, function (result) {
assert.deepEqual(result, expected)
done()
}))
for (var line of expected) {
parser.write(JSON.stringify(line) + '\n')
}
parser.end()
})
it('should handle strange chunks', function (done) {
var parser = jsonlines.parse()
var expected = [
{ test: 'This is a test!' },
{ key: 'value' }
]
parser.pipe(concat({ encoding: 'object' }, function (result) {
assert.deepEqual(result, expected)
done()
}))
parser.write('{ "tes')
parser.write('t": "This is a test!" ')
parser.write('}\n{ "key": "value" }')
parser.write('\n\n\n')
parser.end()
})
it('should ignore empty lines', function (done) {
var parser = jsonlines.parse()
var expected = [
{ first: true, last: false },
{ first: false, last: true }
]
parser.pipe(concat({ encoding: 'object' }, function (result) {
assert.deepEqual(result, expected)
done()
}))
for (var line of expected) {
parser.write(JSON.stringify(line) + '\n\n\n\n\n')
}
parser.end()
})
it('should handle plain values', function (done) {
var parser = jsonlines.parse()
var expected = [ true, false, true, true, false ]
parser.pipe(concat({ encoding: 'object' }, function (result) {
assert.deepEqual(result, expected)
done()
}))
for (var line of expected) {
parser.write(JSON.stringify(line) + '\n')
}
parser.end()
})
it('should emit an error on malformed json', function (done) {
var parser = jsonlines.parse()
var line = '{ "broken": _ }'
parser.on('error', function (err) {
assert.equal(err.source, line)
done()
})
parser.end(line)
})
it('should emit invalid lines', function (done) {
var parser = jsonlines.parse({ emitInvalidLines: true })
var data = '"works"\nbroken\n"ok"'
parser.once('data', function (data) {
assert.equal(data, 'works')
parser.once('invalid-line', function (err) {
assert.equal(err.source, 'broken')
parser.once('data', function (data) {
assert.equal(data, 'ok')
done()
})
})
})
parser.end(data)
})
})