|
2 | 2 |
|
3 | 3 | const path = require('path'); |
4 | 4 | const net = require('net'); |
| 5 | +const readline = require('readline'); |
| 6 | +const {EventEmitter} = require('events'); |
5 | 7 | const _ = require('lodash'); |
6 | | -const { EventEmitter } = require('events'); |
7 | | - |
8 | 8 |
|
9 | 9 | class LightningClient extends EventEmitter { |
10 | 10 | constructor(rpcPath) { |
@@ -44,48 +44,16 @@ class LightningClient extends EventEmitter { |
44 | 44 | }); |
45 | 45 | }); |
46 | 46 |
|
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 | | - } |
55 | | - |
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; |
| 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); |
70 | 53 | } |
71 | 54 |
|
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; |
| 55 | + _self.emit('res:' + data.id, data); |
| 56 | + }); |
89 | 57 | } |
90 | 58 |
|
91 | 59 | increaseWaitTime() { |
@@ -129,7 +97,7 @@ class LightningClient extends EventEmitter { |
129 | 97 | return this.clientConnectionPromise |
130 | 98 | .then(() => new Promise((resolve, reject) => { |
131 | 99 | // Wait for a response |
132 | | - this.once('res:'+callInt, response => { |
| 100 | + this.once('res:' + callInt, response => { |
133 | 101 | if (_.isNil(response.error)) { |
134 | 102 | resolve(response.result); |
135 | 103 | return; |
|
0 commit comments