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 (2014) Building a Command Line Application Getting the Response Body

console.log('BODY:' + chunk) and console.log(chunk)... The difference

when i try to log 'BODY:' + chunk i get a the json file but when i log just the variable chunk i get <Buffer 7b 22 6e 61 6d 65 22 3a...

What is the difference ?

3 Answers

Stefan Osorio
Stefan Osorio
16,419 Points

Those Buffers are instances of Node's Buffer Class, which was designed to handle octet streams. More about Buffers: http://nodejs.org/api/buffer.html

When you concatenate a buffer with a string, you get a string as a result - pretty much the way you get a string when you concatenate a number with a string.

The point of the "BODY " + chunk was (at least i think so) to show that you do actually get multiple chunks, which wouldn't be as obvious if you'd just console.log all the chunks after each other.

Roger Nordqvist
Roger Nordqvist
7,007 Points

This worked when I was playing around:

res.on('data', function(chunk){
    console.log('BODY:', chunk.toString('utf8');
  });

Here is my code

var request = http.get('http://teamtreehouse.com/'+username+'.json',function(res){

   res.on('data', function(chunk){
    console.log(chunk); // <Buffer 7b 22 6e 61 6d 65 22 3a...
    console.log('BODY:' + chunk); // string 
   });

});