DEV Community

Cover image for Node.js Event Emitter

Node.js Event Emitter

Taslan Graham on August 05, 2021

Node's event-driven architecture allows us to execute certain actions when something happens. This is done via objects (called "emitters") which ca...
Collapse
 
sudonitin profile image
Nitin Sahu

What are some practical use of event emitters?

Collapse
 
anaekin profile image
Animesh Jain

Let's say, when your application starts, you are checking the connection to the database and/or doing some other operations which are in different files and you want to inform your app.js file about the connection or pass the information regarding certain operation in multiple files.
You can send an event across the app and wherever you are listening for that event, you can then perform some other operation like retry if db connection fails.
This is useful for communicating between multiple files, passing data between two js files etc.

Collapse
 
zulfadhli4141 profile image
Zulfadhli Zakari

Do you have any example Express project using event emitter?

Thread Thread
 
abodactyl profile image
Abby Redwood

this is effectively what socket.io does.

Collapse
 
rish15 profile image
rish srivastav
this snippet is from pdfmake which creates a buffer and stringBase64

const pdfDoc = printer.createPdfKitDocument(docDefinition);
let chunks = [];
  pdfDoc.on("data", (chunk) => {
    chunks.push(chunk);
  });
  pdfDoc.on("end", () => {
    const result = Buffer.concat(chunks).toString("base64");
    console.log({result})
  });
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ctfrancia profile image
Christian Francia

To drive fellow developers crazy when trying to debug

Collapse
 
sahajranipa1 profile image
sahaj ranipa

Based on some action you can fire the particular event emitter just say on click certain button you want to fire some event or some code then you can use eventemitter I guess.

Collapse
 
stainlessray profile image
stainlessray

Home automation would be one. To extend the example from the article - car on, open garage door and turn on the lights.

Collapse
 
ivandotv profile image
Ivan V. • Edited

Nice article.
For people asking for real world application of the
Event Emitter class, well it enables you to build abstractions like the event bus pattern which enables you to decouple parts of your system (components) or anything else that shouldn't be tightly coupled together.
I've made one such library and wrote an article about it here on dev.
Event Bus Pattern via Native EventEmmiter Class

Collapse
 
yw662 profile image
yw662 • Edited

this is exactly the EventTarget we have in DOM, all except on instead of addEventListener, and we can use Element instead.

And, btw, EventTarget is in node.js since 15.

Collapse
 
kak_kotyavo profile image
KAK KOTYAVO!

I want to say that it is better to use EventEmitter2 as the main solution, since it is really faster.