Today I will tell you about the EventEmitter class. As you know, Node.js has an event-driven programming paradigm. This means that we will define some events and callbacks, our events will be triggered and processed in our program flow. If you ask why such an approach was adopted, it is because JavaScript, which I explained in more detail in my previous article, runs single thread and asynchronous operations must be handled without blocking in some way.
If you ask what all this has to do with the EventEmitter class, this class offers us a structure where we can easily handle asynchronous operations. Actually, this is the Observer Design Pattern implementation.
const EventEmitter = require("events"); class Emitter extends EventEmitter {} const myE = new Emitter(); myE.on("test", () => { console.log("event meydana geldi."); }); myE.on("test", () => { console.log("event meydana geldi."); }); myE.on("test", () => { console.log("event meydana geldi."); }); console.log(myE.eventNames()); myE.emit("test");
Above I wrote a simple example of how to define and call an event. Here, the "on" method actually creates an array called "test" on an empty object (master object).
{ test: [ [Function (anonymous)], [Function (anonymous)], [Function (anonymous)] ] }
Here, the "on" method is called three times with the name eventName and the resulting structure is as above.
As you can guess, the event named "test" is called with the "emit" method. Here, a foreach method returns the test array and calls the functions within it.
So where is this structure used?
For example, in a DOM event;
const btn = document.getElementById("btn"); btn.addEventListener("click", () => { console.log("clicked"); });
For example, in a Network request in Node.js application;
const http = require("http"); const req = http .request( { method: "GET", hostname: "jsonplaceholder.typicode.com", path: "/todos/1" }, (res) => { res.on("data", (chunk) => { console.log(chunk.toString()); }); res.on("end", () => { console.log("response ended."); }); } ) .end();
The above is the detailed content of Node.js EventEmitter. For more information, please follow other related articles on the PHP Chinese website!