brianleroux / tiny-json-http

:anchor: Minimalist HTTP client for JSON payloads.
172 stars 18 forks source link

Set encoding of response body #8

Closed magiksd closed 6 years ago

magiksd commented 6 years ago

Hi,

I'm using your nice module to request an API that return binary data in the response body. I have to encode the data in base64 to correctly use it after, but since you apply "toString" on the response buffer without specifing an encoding, the body comes encoded in utf8, which "kills" the binary data.

In _read.js (line 61) and _write.js (line 58), you could change the code to :

var rawData = Buffer.concat(raw).toString(options.encoding || 'utf8')

This will allow us to specify the encoding used to fetch the data :

tiny.post({
  url: ...,
  encoding: 'base64'
})
magiksd commented 6 years ago

I think a better solution would be to add a boolean option "buffer" to get the response body as a buffer, which allow the use of "toString" with an encoding, or other buffer usage.

try {
  var isJSON = res.headers['content-type'].startsWith('application/json')
  result = Buffer.concat(raw)

  if (!options.buffer) {
    result = isJSON ? JSON.parse(result.toString()) : result.toString()
  }
}
catch (e) {
  err = e
}
brianleroux commented 6 years ago

Like it---will see if I can get to this (PR's also welcome!)

magiksd commented 6 years ago

Sure, I made 2 pull requests :)

brianleroux commented 6 years ago

Thx [again]! published in tiny-json-http@5.3.2 🔥🔥🔥