(data: Uint8Array | string, encoding?: BufferEncoding)
| 160 | } |
| 161 | |
| 162 | function processData(data: Uint8Array | string, encoding?: BufferEncoding) { |
| 163 | let decodedData; |
| 164 | try { |
| 165 | if (data instanceof Uint8Array) { |
| 166 | // Decode only the bytes the view actually spans. A Uint8Array (e.g. a |
| 167 | // Buffer carved from Node's shared pool) is often a view into a larger |
| 168 | // ArrayBuffer, so reading `data.buffer` directly would include unrelated |
| 169 | // bytes outside the view's byteOffset/byteLength range. |
| 170 | decodedData = Buffer.from( |
| 171 | data.buffer, |
| 172 | data.byteOffset, |
| 173 | data.byteLength, |
| 174 | ).toString(); |
| 175 | } else { |
| 176 | decodedData = Buffer.from(data, encoding).toString(); |
| 177 | } |
| 178 | } catch (e) { |
| 179 | // Failed to decode, treat it as simple text. |
| 180 | return {isJSON: false, processedData: data}; |
| 181 | } |
| 182 | |
| 183 | // strip any leading ANSI color codes from the decoded data |
| 184 | // to parse colored JSON objects correctly |
| 185 | decodedData = decodedData.replace(/\x1b[[(?);]{0,2}(;?\d)*./g, ''); |
| 186 | try { |
| 187 | return {isJSON: true, processedData: JSON.parse(decodedData)}; |
| 188 | } catch (e) { |
| 189 | return {isJSON: false, processedData: decodedData}; |
| 190 | } |
| 191 | } |
no test coverage detected