Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 
   });

});