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 Basic Template Engine in Node.js Reading from Files

Kevin Faust
Kevin Faust
15,353 Points

Node.js: maximum call stack size exceeded

hi,

according to the stack trace, the error occurs in the 'profile.js' file on line 29 where i have written body += chunk;

https://w.trhou.se/wbi7lj37om

3 Answers

Seth Kroger
Seth Kroger
56,413 Points

In the on('data') event you have:

        response.on('data', function (chunk) {
            body += chunk;
            this.emit("data", chunk);
        });

vs.

    profileEmitter = this;
    // ... code omitted 

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

Inside the 'data' event handler this isn't the same thing as this outside it. Outside this refers to the Profile object (which you have inheriting from EventEmitter) However inside, according to the documentation "It is important to keep in mind that when an ordinary listener function is called by the EventEmitter, the standard this keyword is intentionally set to reference the EventEmitter to which the listener is attached." That listener isn't attached to the profile, it's attached to the response. By emitting another 'data' event to itself inside it's own handler your causing an infinite recursion.

Matt F.
Matt F.
9,518 Points

Hi Kevin,

Is there anything stopping this from being run infinite times?

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

It looks like your callback is getting called whenever 'data' is emitted and that callback emits 'data' on its last line - meaning that it would cause the function to be called infinitely.

Kevin Faust
Kevin Faust
15,353 Points

I understand now thank you both