Home > Web Front-end > JS Tutorial > Node.js EventEmitter

Node.js EventEmitter

DDD
Release: 2024-12-12 22:16:11
Original
820 people have browsed it

Node.js EventEmitter

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");
Copy after login

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)]
  ]
}
Copy after login

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");
});
Copy after login

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();
Copy after login

The above is the detailed content of Node.js EventEmitter. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template