Detailed explanation of events in Node.js
Related recommendations: "nodejs Tutorial"
The front-end is certainly no stranger to events, binding the scroll event for the window
window.addEventListener('scroll', ev => { console.log(ev); });
Node.js Most asynchronous operations are event-driven. All objects that can trigger events inherit the EventEmitter
class
Event listening
on
Node.js event listening is very similar to jQuery APIemitter.on(eventName, listener)
const ee = new EventEmitter(); ee.on('foo', () => console.log('a'));
- EventEmitter instance will maintain a listener array, and each listener defaults Will be added to the end of the array
- Every time a listener is added, it will not be checked whether it has been added. Calling on multiple times and passing in the same eventName and listener will cause the listener to be added multiple times
prependListener
emitter.prependListener(eventName, listener)
You can add the listener to the head of the listener array through prependListener
const ee = new EventEmitter(); ee.prependListener('foo', () => console.log('a'));
once
If you want the listener to be triggered once and then no longer trigger, you can use once to bind the event
const ee = new EventEmitter(); ee.once('foo', () => console.log('a'));
Event triggering
emitter.emit(eventName[, ... args])
Most of the developer's event-related work in the browser environment is to subscribe to events, that is, to bind the event processing function listener. In Node.js event programming, it is often necessary to create event objects. The actual trigger event. Use the emit method to synchronously call each listener registered to the event named eventName in the order of listener registration, and pass in the provided parameters
const EventEmitter = require('events'); const myEmitter = new EventEmitter(); // 第一个监听器。 myEmitter.on('event', function firstListener() { console.log('第一个监听器'); }); // 第二个监听器。 myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`第二个监听器中的事件有参数 ${arg1}、${arg2}`); }); // 第三个监听器 myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`第三个监听器中的事件有参数 ${parameters}`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // 第一个监听器 // 第二个监听器中的事件有参数 1、2 // 第三个监听器中的事件有参数 1, 2, 3, 4, 5
this points to
eventEmitter.emit()
The method can pass any number of parameters to the listener. this
The keyword will be pointed to the EventEmitter instance bound to the listener
const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { console.log(a, b, this, this === myEmitter); // 打印: // a b MyEmitter { // domain: null, // _events: { event: [Function] }, // _eventsCount: 1, // _maxListeners: undefined } true }); myEmitter.emit('event', 'a', 'b');
You can also use ES6 arrow functions as listeners. But this
keyword will not point to the EventEmitter instance:
const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // 打印: a b {} }); myEmitter.emit('event', 'a', 'b');
Asynchronous call
EventEmitter
Call all listeners synchronously in the order of registration, so that To ensure the correct ordering of events, the listener can use the setImmediate()
and process.nextTick()
methods to switch to asynchronous operation mode
const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { setImmediate(() => { console.log('异步地发生'); }); }); myEmitter.emit('event', 'a', 'b');
Event unloading
Node.js provides several methods for uninstalling event bindings
off/removeListener
The off method is an alias of the removeListener method and is used to clean up event bindings emitter.removeListener(eventName, listener)
const callback = (stream) => { console.log('已连接'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);
removeListener() will only remove at most one listener from the listener array. If a listener is added multiple times to the listener array for a specified eventName, removeListener() must be called multiple times to remove all instances
removeAllListeners
emitter. removeAllListeners([eventName])
Remove the listener of the specified eventName event. If eventName is not specified, remove all listeners of the event object. You can get the eventName array on the event object through emitter.eventNames()
const EventEmitter = require('events'); const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); myEE.eventNames().forEach(eventName => myEE.removeAllListeners);
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of Detailed explanation of events in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine
![Event ID 4660: Object deleted [Fix]](https://img.php.cn/upload/article/000/887/227/168834320512143.png?x-oss-process=image/resize,m_fill,h_207,w_330)
Some of our readers encountered event ID4660. They're often not sure what to do, so we explain it in this guide. Event ID 4660 is usually logged when an object is deleted, so we will also explore some practical ways to fix it on your computer. What is event ID4660? Event ID 4660 is related to objects in Active Directory and will be triggered by any of the following factors: Object Deletion – A security event with Event ID 4660 is logged whenever an object is deleted from Active Directory. Manual changes – Event ID 4660 may be generated when a user or administrator manually changes the permissions of an object. This can happen when changing permission settings, modifying access levels, or adding or removing people or groups

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

On iPhones running iOS 16 or later, you can display upcoming calendar events directly on the lock screen. Read on to find out how it's done. Thanks to watch face complications, many Apple Watch users are used to being able to glance at their wrist to see the next upcoming calendar event. With the advent of iOS16 and lock screen widgets, you can view the same calendar event information directly on your iPhone without even unlocking the device. The Calendar Lock Screen widget comes in two flavors, allowing you to track the time of the next upcoming event, or use a larger widget that displays event names and their times. To start adding widgets, unlock your iPhone using Face ID or Touch ID, press and hold

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

How to use Node.js for front-end application development? The following article will introduce you to the method of developing front-end applications in Node, which involves the development of presentation layer applications. The solution I shared today is for simple scenarios, aiming to allow front-end developers to complete some simple server-side development tasks without having to master too much background knowledge and professional knowledge about Node.js, even if they have no coding experience.
