Populate XHR response property with binary data #198
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Always populating
response
is a hack (one should really request it viaresponseType
), but a useful one. For my particular use case I wanted to do a synchronous XHR, in a worker thread, returning a binary data response back. It turned out to be surprisingly difficult to get all three requirements working at once with the various packages that I tried.This PR is similar to the solution in #155, populating
response
usingBuffer.concat
, but with some further improvements.By setting
response.setEncoding('binary')
, the received data is not lossy encoded to 'utf8' before being stored in the response Buffer. This fixes a problem that exists even in #155 where certain bytes are incorrectly converted in the response buffer, irreversibly becoming 0xFD.Since the default encoding is now binary, the response data is explicitly encoded to utf8 when storing it in
responseText
, maintaining the default behaviour of the module before the change.The same changes are made to the synchronous version of the code. Since part of this process is for data to be temporarily written out to a file, the data buffer is written out base64 encoded here to avoid the same issues with utf8 encoding/decoding when loading the data back in from the file.