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 ??

2 Answers

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'...

Pepe Toño
Pepe Toño
13,330 Points

In practice, get method just returns a response in JSON format by default; However, I think the TreeHouse API endpoint ( returns a kind of custom JSON object where is needed to format de chunk of data