Skip to content

Commit 0a2b027

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 1a8d3ba commit 0a2b027

File tree

1 file changed

+6
-41
lines changed

1 file changed

+6
-41
lines changed

index.js

Lines changed: 6 additions & 41 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 _ = require('lodash');
67
const { EventEmitter } = require('events');
78

@@ -44,48 +45,12 @@ class LightningClient extends EventEmitter {
4445
});
4546
});
4647

47-
this.client.on('data', data => {
48-
_.each(LightningClient.splitJSON(data.toString()), str => {
49-
let dataObject = {};
50-
try {
51-
dataObject = JSON.parse(str);
52-
} catch (err) {
53-
return;
54-
}
48+
readline.createInterface({ input: this.client }).on('line', str => {
49+
try { var data = JSON.parse(''+str); }
50+
catch (err) { return _self.emit('error', 'Invalid JSON: '+str); }
5551

56-
_self.emit('res:'+dataObject.id, dataObject)
57-
});
58-
});
59-
}
60-
61-
static splitJSON(str) {
62-
const parts = [];
63-
64-
let openCount = 0;
65-
let lastSplit = 0;
66-
67-
for (let i = 0; i < str.length; i++) {
68-
if (i > 0 && str.charCodeAt(i - 1) === 115) { // 115 => backslash, ignore this character
69-
continue;
70-
}
71-
72-
if (str[i] === '{') {
73-
openCount++;
74-
} else if (str[i] === '}') {
75-
openCount--;
76-
77-
if (openCount === 0) {
78-
const start = lastSplit;
79-
const end = i + 1 === str.length ? undefined : i + 1;
80-
81-
parts.push(str.slice(start, end));
82-
83-
lastSplit = end;
84-
}
85-
}
86-
}
87-
88-
return parts.length === 0 ? [str] : parts;
52+
_self.emit('res:'+data.id, data);
53+
})
8954
}
9055

9156
increaseWaitTime() {

0 commit comments

Comments
 (0)