Node.js and listeners: Understanding

Hello,

Currently reading away to prepare to do the backend projects. If I understand, this

request.on('data', (chunk) => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body).toString();
  // at this point, `body` has the entire request body stored in it as a string
});

is the same as

request.on('data', (chunk) => {
  body.push(chunk);
});

request.on('end', () => {
  body = Buffer.concat(body).toString();
  // at this point, `body` has the entire request body stored in it as a string
});

But why? The first example looks like it’s chained together rather than two separate expressions.

Okay, so let’s look at the second little bit

request.on('end', () => {
  body = Buffer.concat(body).toString();
  // at this point, `body` has the entire request body stored in it as a string
});

It’s doing something to the value of request.

Now, let’s take a look at the first bit

request.on('data', (chunk) => {
  body.push(chunk);
})

When we look at the documentation, you can see that .on() is a method of request (an EventEmitter) which returns something. It’s a bit like Math.sqrt(9), which returns 3.

In this case, however, the method does something and returns a value. What does it return, though? Well, it turns out it returns the value of request.

So basically, we can swap in

request.on(...)

for

request

and it’ll do the same thing.

The first one, however, also adds an event listener. That’s why you can chain them. Because each one’s return value is the same as the starting request that you started the chaining with. :slightly_smiling_face:

1 Like

Thanks for the detailed and quick reply!

So, if I understand what you’re explaining

request.on(…) Returns a reference to the EventEmitter, so that calls can be chained. (from the documentation, thanks :beers:)

In other words, request.on(…) returns request (the EventEmitter).

Very loosely similar to: request += request.on(…) ?

In other words, request.on(…) returns request (the EventEmitter).

Yep!

request += request.on(…)

Not sure what you mean by incrementing something which isn’t really good with addition (an EventEmitter), sorry

I guess I just meant request becomes request with a listener. The first point was clearer and captured the meaning.

Anyhow! That clears it up and it makes sense. :beers: Thank you.