diff --git a/index.js b/index.js index f65d3e3..cc35202 100644 --- a/index.js +++ b/index.js @@ -2,9 +2,11 @@ const path = require('path'); const net = require('net'); +const readline = require('readline'); +const {EventEmitter} = require('events'); const _ = require('lodash'); -class LightningClient { +class LightningClient extends EventEmitter { constructor(rpcPath) { if (!path.isAbsolute(rpcPath)) { throw new Error('The rpcPath must be an absolute path'); @@ -14,6 +16,7 @@ class LightningClient { console.log(`Connecting to ${rpcPath}`); + super(); this.rpcPath = rpcPath; this.reconnectWait = 0.5; this.reconnectTimeout = null; @@ -41,55 +44,16 @@ class LightningClient { }); }); - this.waitingFor = {}; - - this.client.on('data', data => { - _.each(LightningClient.splitJSON(data.toString()), str => { - let dataObject = {}; - try { - dataObject = JSON.parse(str); - } catch (err) { - return; - } - - if (!_.isFunction(_self.waitingFor[dataObject.id])) { - return; - } - - _self.waitingFor[dataObject.id].call(_self, dataObject); - delete _self.waitingFor[dataObject.id]; - }); - }); - } - - static splitJSON(str) { - const parts = []; - - let openCount = 0; - let lastSplit = 0; - - for (let i = 0; i < str.length; i++) { - if (i > 0 && str.charCodeAt(i - 1) === 115) { // 115 => backslash, ignore this character - continue; + readline.createInterface({input: this.client}).on('line', str => { + let data; + try { + data = JSON.parse(str); + } catch (err) { + return _self.emit('error', 'Invalid JSON: ' + str); } - if (str[i] === '{') { - openCount++; - } else if (str[i] === '}') { - openCount--; - - if (openCount === 0) { - const start = lastSplit; - const end = i + 1 === str.length ? undefined : i + 1; - - parts.push(str.slice(start, end)); - - lastSplit = end; - } - } - } - - return parts.length === 0 ? [str] : parts; + _self.emit('res:' + data.id, data); + }); } increaseWaitTime() { @@ -131,22 +95,20 @@ class LightningClient { // Wait for the client to connect return this.clientConnectionPromise - .then(() => { + .then(() => new Promise((resolve, reject) => { // Wait for a response - return new Promise((resolve, reject) => { - this.waitingFor[callInt] = response => { - if (_.isNil(response.error)) { - resolve(response.result); - return; - } - - reject(new Error(response.error)); - }; - - // Send the command - _self.client.write(JSON.stringify(sendObj)); + this.once('res:' + callInt, response => { + if (_.isNil(response.error)) { + resolve(response.result); + return; + } + + reject(new Error(response.error)); }); - }); + + // Send the command + _self.client.write(JSON.stringify(sendObj)); + })); } devBlockheight() {