Skip to content

Instantly share code, notes, and snippets.

@FredrikAugust
Created February 22, 2015 01:03
Show Gist options
  • Save FredrikAugust/da0550ac3a297714e44a to your computer and use it in GitHub Desktop.
Save FredrikAugust/da0550ac3a297714e44a to your computer and use it in GitHub Desktop.
Treehouse Node.js Practice
// Store the profile getting here
// Require libs
var http = require("http");
// Define the printMessage function, self-explanatory
function printMessage(username, badgeCount, points) {
var message = username + " has " + badgeCount + " total badge(s) and " + points + " points in JavaScript";
console.log(message);
}
// Error handling
function showError(error) {
console.error(error.message);
}
// Connect to API URL
function get(username) {
var request = http.get("http://teamtreehouse.com/" + username + ".json", function (response) {
var body = "";
response.on("data", function (chunk) {
body += chunk;
});
response.on("end", function () {
if (response.statusCode === 200) {
try {
var profile = JSON.parse(body);
printMessage(username, profile.badges.length, profile.points.JavaScript);
} catch (error) {
showError(error);
}
} else {
showError({ message: "There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")" });
}
});
});
// If error
request.on("error", showError);
}
get("mrmadsenmalmo");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment