Skip to content

Commit d543474

Browse files
committed
Use readline to separate JSON response objects
- JSON responses are newline-delimited by c-lighting and can't contain newlines, so this achieves the same in a simpler and more efficient manner. - The previous method would break with something like { "key": "}" } - The previous method would break if a single JSON response is split across multiple `data` events (possible with large responses).
1 parent 38a7eed commit d543474

File tree

1 file changed

+9
-40
lines changed

1 file changed

+9
-40
lines changed

index.js

Lines changed: 9 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
const path = require('path');
44
const net = require('net');
5+
const readline = require('readline');
56
const {EventEmitter} = require('events');
67
const _ = require('lodash');
78

@@ -43,48 +44,16 @@ class LightningClient extends EventEmitter {
4344
});
4445
});
4546

46-
this.client.on('data', data => {
47-
_.each(LightningClient.splitJSON(data.toString()), str => {
48-
let dataObject = {};
49-
try {
50-
dataObject = JSON.parse(str);
51-
} catch (err) {
52-
return;
53-
}
54-
55-
_self.emit('res:' + dataObject.id, dataObject);
56-
});
57-
});
58-
}
59-
60-
static splitJSON(str) {
61-
const parts = [];
62-
63-
let openCount = 0;
64-
let lastSplit = 0;
65-
66-
for (let i = 0; i < str.length; i++) {
67-
if (i > 0 && str.charCodeAt(i - 1) === 115) { // 115 => backslash, ignore this character
68-
continue;
47+
readline.createInterface({input: this.client}).on('line', str => {
48+
let data;
49+
try {
50+
data = JSON.parse(str);
51+
} catch (err) {
52+
return _self.emit('error', 'Invalid JSON: ' + str);
6953
}
7054

71-
if (str[i] === '{') {
72-
openCount++;
73-
} else if (str[i] === '}') {
74-
openCount--;
75-
76-
if (openCount === 0) {
77-
const start = lastSplit;
78-
const end = i + 1 === str.length ? undefined : i + 1;
79-
80-
parts.push(str.slice(start, end));
81-
82-
lastSplit = end;
83-
}
84-
}
85-
}
86-
87-
return parts.length === 0 ? [str] : parts;
55+
_self.emit('res:' + data.id, data);
56+
});
8857
}
8958

9059
increaseWaitTime() {

0 commit comments

Comments
 (0)