Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Node.js Basics 2017 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,814 Points

In practice, get method just returns a response in JSON format by default; However, I think the TreeHouse API endpoint (https://teamtreehouse.com/username.json) returns a kind of custom JSON object where is needed to format de chunk of data