diff --git a/CHANGES.md b/CHANGES.md index 44bf101..5cdf04f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,7 @@ +## v6.2.2 + +- Fixes parsing for large HTTP chunks. + ## v6.2.1 - Emits `partialTranscription` and `fullTranscription` events. diff --git a/lib/wit.js b/lib/wit.js index e4f1d2c..80ee009 100644 --- a/lib/wit.js +++ b/lib/wit.js @@ -101,9 +101,7 @@ class Wit extends EventEmitter { while (null !== (chunk = bodyStream.read())) { contents += chunk.toString(); } - for (const {error, intents, text} of splitHttpChunks( - contents, - ).map(x => JSON.parse(x))) { + for (const {error, intents, text} of parseResponse(contents)) { if (!(error || intents)) { logger.debug('[speech] partialTranscription:', text); this.emit('partialTranscription', text); @@ -119,10 +117,7 @@ class Wit extends EventEmitter { return req .then(response => Promise.all([response.text(), response.status])) - .then(([contents, status]) => [ - JSON.parse(splitHttpChunks(contents).pop()), - status, - ]) + .then(([contents, status]) => [parseResponse(contents).pop(), status]) .catch(e => e) .then(makeWitResponseHandler(logger, 'speech')); } @@ -177,12 +172,25 @@ const encodeURIParams = params => .map(([key, value]) => key + '=' + encodeURIComponent(value)) .join('&'); -const splitHttpChunks = response => - response +const parseResponse = response => { + const chunks = response .split('\r\n') .map(x => x.trim()) .filter(x => x.length > 0); + let prev = ''; + let jsons = []; + for (const chunk of chunks) { + try { + prev += chunk; + jsons.push(JSON.parse(prev)); + prev = ''; + } catch (_e) {} + } + + return jsons; +}; + const validate = opts => { if (!opts.accessToken) { throw new Error( diff --git a/package.json b/package.json index 04ddf74..237b98c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "node-wit", - "version": "6.2.1", + "version": "6.2.2", "description": "Wit.ai Node.js SDK", "keywords": [ "wit",