From 54aa74267ffc6519a52cbbba37203e2194a10d9d Mon Sep 17 00:00:00 2001 From: achorein Date: Mon, 6 Nov 2023 14:28:08 +0100 Subject: [PATCH] handle hexadecimal write and read --- lib/connection.js | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/connection.js b/lib/connection.js index 40780ec..fce73e9 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -46,16 +46,20 @@ class Connection { send (content, opts) { if (this.state !== Connection.states().OPEN) { return Promise.reject(new Error('instance not in state OPEN')) - } else if (typeof content !== 'string') { - return Promise.reject(new Error('first argument must be a string')) + } else if (typeof content !== 'string' && !Buffer.isBuffer(content)) { + return Promise.reject( + new Error('first argument must be a string or a Buffer') + ) } opts = opts || {} const terminator = opts.terminator || '' const timeoutInit = opts.timeoutInit || 100 const timeoutRolling = opts.timeoutRolling || 10 + const fixedRespBytesLength = opts.fixedRespBytesLength || -1 this.state = Connection.states().INUSE let chunks = '' + const bytes = [] let timer return new Promise((resolve, reject) => { @@ -65,11 +69,15 @@ class Connection { timer = null } chunks = chunks.concat(data) + bytes.push(data.toString('hex').toUpperCase()) if (terminator) { const ix = chunks.indexOf(terminator) - if (ix > 0 && ix === chunks.length + 1) { + if ( + bytes.length >= fixedRespBytesLength || + (ix > 0 && ix === chunks.length + 1) + ) { this.state = Connection.states().OPEN - resolve(chunks) + resolve(fixedRespBytesLength > 0 ? bytes.join('') : chunks) } else if (ix > 0 && ix !== chunks.length + 1) { this.state = Connection.states().ERROR reject(new Error('Terminator detected in the middle of answer. Check your options')) @@ -77,7 +85,7 @@ class Connection { } } timer = setTimeout(() => { - resolve(chunks) + resolve(fixedRespBytesLength > 0 ? bytes.join('') : chunks) }, timeoutRolling) }) @@ -86,7 +94,7 @@ class Connection { reject(new Error(err)) } timer = setTimeout(() => { - resolve(chunks) + resolve(fixedRespBytesLength > 0 ? bytes.join('') : chunks) }, timeoutInit) }) })