JavaScript Node.js Basics Building a Command Line Application Capturing Command Line Arguments

Akshay Bhamare
Akshay Bhamare
15,616 Points

Accessing the response argument as an object

Hi, I don't understand that after getting a response in the get method as an object why are we still again creating a new object by parsing data in JSON?? How the argument(response) is different than the profile object ??

1 Answer

When you perform

response.on('data', data => {
 // here we get the data as a buffer object
}

what you get is the data (the response) as a buffer. A buffer is not legible to human eyes so you need to parse it to a string object. Then, in the end callback method you parse the string response into a JSON object

response.on('end', () => {
  // Parse the data
  const profile = JSON.parse(body);
  // Print the data
  printMessage(username, profile.badges.length, profile.points.JavaScript);
});

And to claritfy, to access the body of the response you need to use response.on('nameofthecalback'...