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 trialSander Heieren
12,613 PointsWhy can I not see value of body? Only prints out empty string. Does it not get added to the the string for every chunk?
HERE IS THE CODE:
const https = require("https");
const username = 'chalkers';
function printMessage(username, badge, points){
const message = `${username} has ${badge} badges and ${points} points in js`
console.log(message);
}
//connect to api
const request = https.get(`https://teamtreehouse.com/${username}.json`, response =>{
let body = "";
response.on('data', data =>{
body += data.toString();
})
//response.on('end', () =>{
//console.log(body);
// })
console.log(body); // THIS ONE HERE. WHY DOES IT NOT GET ADDED TO BODY?
});
Rich Donnellan
Treehouse Moderator 27,708 PointsQuestion updated with code formatting. Check out the Markdown Cheatsheet below the Add an Answer submission for syntax examples, or choose Edit Question from the three dots next to Add Comment to see how I improved the readability.
1 Answer
James Crosslin
Full Stack JavaScript Techdegree Graduate 16,882 PointsThe answer is because it only console logs once and before any data is returned. Your 'get' request is an asynchronous function. It sends out a request and body exists as an empty string until you start getting responses. But your console.log(body) method does not understand that. Console.log(body) is next on the call stack before the data returns, so it runs one time and returns the value of body, which is an empty string. If you want to console log each stage of the body concatenation, you can do this:
const https = require("https")
const username = "chalkers"
function printMessage(username, badgeCount, points) {
const message = `${username} has ${badgeCount} badges and ${points} points in JavaScript`
console.log(message)
}
//Connect to the API URL (https://teamtreehouse.com/username.json)
const request = https.get(
`https://teamtreehouse.com/${username}.json`,
(response) => {
let body = ""
response.on("data", (data) => {
body += data.toString()
console.log(body) // <--- This is where you have to place your log
})
}
)
This will print the entirety of your body variable each time a new round of data comes in. Your console.log(body) has to be within the scope of the data transmission and reception method, '.on()'.
Sander Heieren
12,613 PointsSander Heieren
12,613 Pointsvery sorry for bad formatting...