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 Build a Simple Dynamic Site with Node.js Creating a Simple Server in Node.js Preparing & Planning

Vitaly Khe
Vitaly Khe
7,160 Points

ES6 ECMA2015 version. pls check out

profile.js

const EventEmitter = require("events");
const https = require("https");
const http = require("http");
const util = require("util");

class Profile extends EventEmitter {

    constructor(username) {
      super();
      // need for  calling the  methods of EventEmitter
      let profileInstanceContext = this;

      const request = https.get("https://teamtreehouse.com/" + username + ".json", function(response) {
        let body = "";

        if (response.statusCode !== 200) {
          request.abort();
          //Status Code Error
          profileInstanceContext.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));
        }

        //Read the data
        response.on('data', function (chunk) {
          body += chunk;
          profileInstanceContext.emit("data", chunk);
        });

        response.on('end', function () {
          if(response.statusCode === 200) {
            try {
              //Parse the data
              const profile = JSON.parse(body);
              profileInstanceContext.emit("end", profile);
            } catch (error) {
              profileInstanceContext.emit("error", error);
            }
          }
        }).on("error", function(error){
          profileInstanceContext.emit("error", error);
        });
      });
    }

    //Connect to the API URL (https://teamtreehouse.com/username.json)
}

module.exports = Profile;