Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node .js event


May 10, 2021 Node.js


Table of contents


Node .js event

Node .js all asynchronous I/O operations send an event to the event queue when they are complete.

Node .js many objects in the database distribute events: a net. T he Server object distributes an event each time there is a new connection, and an fs.readStream object emits an event when the file is opened. A ll of these event-generating objects are events. A n example of EventEmitter. Y ou can use require ("events"); to access the module.

Let's illustrate the use of EventEmitter with a simple example:
//event.js 
var EventEmitter = require('events').EventEmitter; 
var event = new EventEmitter(); 
event.on('some_event', function() { 
    console.log('some_event occured.'); 
}); 
setTimeout(function() { 
    event.emit('some_event'); 
}, 1000); 

Run this code, and after 1 second the console outputs 'some_event'. T he principle is that the event object registers a listener for event some_event, and then we send event some_event to the event object after 1000 milliseconds through setTimeout, which calls the some_event listener.


EventEmitter

The events module provides only one object: events. E ventEmitter。 At the heart of EventEmitter is the encapsulation of event emission and event listener capabilities.

Each event in EventEmitter consists of an event name and several parameters, which are a string that usually expresses certain semantics. For each event, EventEmitter supports several event listeners.

When an event is emitted, the event listener registered to the event is called in turn, and the event parameter is passed as a callback function argument.

Let's explain the process with the following example:

var events = require('events'); 
var emitter = new events.EventEmitter(); 
emitter.on('someEvent', function(arg1, arg2) { 
    console.log('listener1', arg1, arg2); 
}); 
emitter.on('someEvent', function(arg1, arg2) { 
 console.log('listener2', arg1, arg2); 
}); 
emitter.emit('someEvent', 'byvoid', 1991); 

The result of the run is:

listener1 byvoid 1991 
listener2 byvoid 1991 

In the example above, emitter registers two event listeners for the event someEvent and then fires the someEvent event. A s a result of the run, you can see that two event listener callback functions are called one after another. T his is the simplest use of EventEmitter.

The API commonly used by EventEmitter

EventEmitter.on (event, listener), emitter.addListener (event, listener) register a listener for the specified event, receive a string event, and a callback function listener.

server.on('connection', function (stream) {
  console.log('someone connected!');
});
EventEmitter.emit (event, s arg1), s arg2, s.... ) launches the event event, transmits several optional parameters to the parameter table of the event listener.

EventEmitter.once (event, listener) registers a single listener for a specified event, i.e. the listener is triggered only once at most, and the listener is dismissed immediately after the trigger.

server.once('connection', function (stream) {
  console.log('Ah, we have our first user!');
});

EventEmitter.removeListener (event, listener) removes a listener for a specified event, which must be a registered listener for that event.

var callback = function(stream) {
  console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);

EventEmitter.removeAllListeners removes all listeners for all events and, if events are specified, all listeners for specified events.


Error event

EventEmitter defines a special event error that contains the semantics of "error" and we typically emit an error event when we encounter an exception.

When the error is fired, EventEmitter specifies that node.js will treat it as an exception, exit the program, and print the call stack if there is no sounding listener.

We generally set up listeners for objects that emit error events to avoid the entire program crashing after an error. For example:

var events = require('events'); 
var emitter = new events.EventEmitter(); 
emitter.emit('error'); 

The runtime displays the following error:

node.js:201 
throw e; // process.nextTick error, or 'error' event on first tick 
^ 
Error: Uncaught, unspecified 'error' event. 
at EventEmitter.emit (events.js:50:15) 
at Object. (/home/byvoid/error.js:5:9) 
at Module._compile (module.js:441:26) 
at Object..js (module.js:459:10) 
at Module.load (module.js:348:31) 
at Function._load (module.js:308:12) 
at Array.0 (module.js:479:10) 
at EventEmitter._tickCallback (node.js:192:40) 

Inherit EventEmitter

Most of the time we don't use EventEmitter directly, but inherit it in an object. As long as the core modules that support incident response, including fs, net, http, are sub-classes of EventEmitter.

Why would you do that? There are two reasons:

First, object implementation events with an entity capability conform to semantics, and the monitoring and emission of events should be a method of an object.

Second, JavaScript's object mechanism is prototype-based, supporting partial multi-inheritance, and inheriting EventEmitter does not disrupt the object's original inheritance relationship.