EventEmitter module in Node.js: basic concepts, usage methods and common application scenarios

Node.js is an event-driven JavaScript runtime environment widely used for server-side development. Node.js has a powerful built-in event module called EventEmitter. EventEmitter provides an ability to handle events and implement custom events.

This article will introduce the EventEmitter module in Node.js in detail, including its basic concepts, usage methods and common application scenarios.

The basic concept of EventEmitter

Events and Listeners

In Node.js, an event refers to the occurrence of a specific action or state in a program. For example, when a new HTTP request arrives at the server, we can think of it as an event. Events can be monitored, and when an event occurs, the listener will execute the corresponding callback function.

The EventEmitter module provides a mechanism for registering listeners and firing events. It is a constructor, we need to create an EventEmitter instance before we can use its methods.

Send and receive events

The core function of an EventEmitter instance is to send and receive events. Events are sent by invoking instance emitmethods, and events are received by listening to events through listeners and executing corresponding callback functions.

Each event has a name, and when the event is sent, it can be passed some data as parameters to the listener.

How to use EventEmitter

Create an EventEmitter instance

To use the EventEmitter module, you first need to import the module into your project:

const EventEmitter = require('events');

Then, create an EventEmitter object by instantiating the EventEmitter class:

const myEmitter = new EventEmitter();

Now, we can use myEmitterthe object to send events and register listeners.

register listener

To listen to events, you need to use ona method or addListenermethod to register the listener. These two methods are completely equivalent and you can choose to use either one.

Here's an example that demonstrates how to listen to events and execute corresponding callback functions:

myEmitter.on('event', (arg1, arg2) => {
    
    
  console.log('触发了event事件', arg1, arg2);
});

In the above example, when eventthe event named occurs, the callback function passed in will be executed and the values ​​of the two parameters will be printed.

send event

To send an event, a method is required emit. emitThe method accepts two parameters: the event name and optional parameters to pass to the listener.

Here is an example showing how to send events:

myEmitter.emit('event', '参数1', '参数2');

In the above example, we sent eventthe event named and passed two parameters to the listener.

one-time event listener

Sometimes, we just want an event to be removed immediately after being fired once. onceOne-time event listeners can be registered using the method.

Here's an example showing how to onceregister a one-time event listener using the method:

myEmitter.once('event', (arg1, arg2) => {
    
    
  console.log('只触发一次的事件', arg1, arg2);
});

In the above example, when eventthe event named is triggered for the first time, the callback function passed in will be executed and the values ​​of the two parameters will be printed out. After that, the listener will be automatically removed and will no longer listen to subsequent events.

Common application scenarios of EventEmitter

custom event

The EventEmitter module allows us to create custom events to meet specific needs. By using emitmethods and corresponding listeners, we can implement a more flexible event handling mechanism.

Here is an example showing how to create a custom event and register a listener:

class MyCustomEmitter extends EventEmitter {
    
    }

const myCustomEmitter = new MyCustomEmitter();

myCustomEmitter.on('custom_event', () => {
    
    
  console.log('自定义事件被触发了');
});

myCustomEmitter.emit('custom_event');

In the above example, we created a custom EventEmitter class and instantiated an object myCustomEmitter. Then, we registered a custom_eventlistener named custom event, when the event is triggered, the callback function will be executed.

error handling

The EventEmitter module can also be used to handle errors. When an error occurs in an operation, we can trigger an error event and pass the error information to the listener for processing.

Here's an example that demonstrates how to handle error events:

const fs = require('fs');

const myFileEmitter = new EventEmitter();

myFileEmitter.on('error', (err) => {
    
    
  console.error('发生错误:', err);
});

fs.readFile('file_not_exists.txt', (err, data) => {
    
    
  if (err) {
    
    
    myFileEmitter.emit('error', err);
  }
});

In the above example, we use the Node.js fsmodule to read a file that does not exist, and emittrigger an error event through the method. In the listener for the error event, we print out the error message.

in conclusion

The EventEmitter module for Node.js provides a powerful mechanism for handling events and implementing custom events. By registering listeners and sending events, we can write event-driven code flexibly.

This article introduces the basic concept, usage and common application scenarios of EventEmitter. I hope that through this article, you have a more detailed understanding of EventEmitter in Node.js and can use it flexibly in actual projects.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/131894893