Reputation: 51383
parseResponse = (response, cb) ->
output = ''
response.setEncoding('utf8')
response.on 'data', (chunk) -> output += chunk
response.on 'end', ->
j = JSON.parse(output)
result = j.results[0]
cb(result)
I'm trying to understand what this is doing and why it is necessary in a module I'm using. The response being passed in is from an http get.
Thanks
Upvotes: 0
Views: 85
Reputation: 25572
This function processes a response (instance of the ClientResponse
class) being received via HTTP.
response.setEncoding('utf-8')
Indicates the desired transfer encoding (UTF-8). Chunks passed to the data
event will be sent in this encoding.
response.on 'data', (chunk) -> output += chunk
Sets up a callback for processing data chunks. Each "chunk" of a string received is appended to the output
string variable.
response.on 'end', ->
Sets another callback which acts on the completely transferred data.
j = JSON.parse(output)
result = j.results[0]
The received data is assumed to be JSON and parsed as such. The first element of the parsed array is retrieved.
cb(result)
The callback cb
originally provided to the function is called with this data found in the JSON object.
Upvotes: 4