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

Filipe Costa
Filipe Costa
10,071 Points

util.inherits() is being discouraged... (solution)

Hi! While going through the profile.js file, in my journey to try to understand how event emitters work, I found out that util.inherits method is being discouraged in favour of ES6 classes and extends syntax. This is my solution to the code:

const Event = require("events");
const https = require("https");
const http = require("http");

/**
 * Custom Event to get a Treehouse students profile
 * @param username
 * @constructor
 */

class Profile extends Event {
    constructor(username) {
     super();
     const profileEmmiter = this;
     //Connect to the API URL (https://teamtreehouse.com/username.json)
     const request = https.get("https://teamtreehouse.com/" + username + ".json", (response) => {
      let body = "";
      if (response.statusCode !== 200) {
       request.abort();
       //Status Code Error
       profileEmmiter.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));
      }
      //Read the data
      response.on('data', (chunk) => {
       body += chunk;
       profileEmmiter.emit("data", chunk);
      });

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

module.exports = Profile;

I hope this helps!