Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Build a Simple Dynamic Site with Node.js Creating a Simple Server in Node.js Preparing & Planning

ES6 version of profile.js

The code of the video is deprecated, use this version instead. In order to understand EventEmitter, please refers to any video on YouTube explaining EventEmitter in Node.js.

import EventEmitter from 'events';
import { get, statusCode } from 'https';
import { STATUS_CODES } from 'http';

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

        const request = get(`https://teamtreehouse.com/${username}.json`, res => {
            let body = '';

            if (res.statusCode !== 200) {
                request.abort();
                profileInstanceContext.emit('error', new Error(`There was an error getting the profile for ${username}. (${STATUS_CODES[statusCode]})`))
            }

            res.on('data', chunk => {
                body += chunk;
                profileInstanceContext.emit('data', chunk);
            });

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

export default Profile;
Ben McMahan
Ben McMahan
7,838 Points

This throws an error -

C:\Users\Benjamin\WebstormProjects\dynamic\profile.js:1
import EventEmitter from 'events';

SyntaxError: Cannot use import statement outside a module

1 Answer

Armend Azemi
Armend Azemi
24,545 Points

Another point to notice is that as of 2022, the request URL is wrong, the correct URL to get profiles should now be

let request = https.get(`https://teamtreehouse.com/profiles/${username}.json

Notice that the /profiles/.