nodejs Events -https://nodejs.org/api/events.html

本文深入探讨了Node.js中核心API的异步事件驱动架构,介绍了如何使用EventEmitter类实现事件监听与触发,并讨论了监听者函数的同步执行机制及错误处理的最佳实践。

NODE的事件机制

许多Nodejs的核心API构建在一个异步事件驱动架构上,此架构上有很多周期性发射事件的对象(被称为事件发射器),发射出的事件会导致相应的函数对象(称为事件监听者)被调用。

例如,一个 net.Server 对象,每次有同伴连接它时,它就会发射一个事件。一个fs.ReadStream对象会在某个文件被打开时发射一个事件,一个 stream 对象会在数据可读时发射一个事件。

所有发射事件的对象都是 EventEmitter 类的实例,这些对象有一个eventEmitter.on()方法,此方法允许将一个或者多个函数附着在对象发射的事件上。一般来说,事件名一般为驼峰命名的字符串,但是,任何合法的js属性key都可以作为事件名。

EventEmitter 对象发射一个事件时,附着在事件之上的函数就会同步执行。监听者返回的任何数据都会被忽略、丢弃。

下列例子展示了一个简单的 EventEmitter 实例,它只有一个监听者。eventEmitter.on()方法用来注册监听者, eventEmitter.emit() 方法用来触发事件。

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');

向监听者传入参数和this

eventEmitter.emit()方法允许向监听者传入任意数量的参数。值得注意的是,当一个监听函数被调用时,this指向这个函数所在的EventEmitter对象。

myEmitter.on('event', function(a,b){
    console.log('an event occurred!');
    console.log(a, b, this);
});
myEmitter.emit('event',1,2);
这时this指向EventEmitter对象。
myEmitter.on('event', (a,b) => {
    console.log('an event occurred!');
    console.log(a, b, this);
});
myEmitter.emit('event',1,2);
这时this指向{}.

异步 VS 同步

EventListener对象会按照注册的顺序同步执行所有监听函数,这有利于保证事件的正确调用顺序,防止出现逻辑错误。但是在合适的时候,监听函数可以通过setImmediate() or process.nextTick() 方法进行异步调用。

只会执行一次的监听者

利用eventEmitter.once()方法,注册的函数监听者只会被执行一次。

错误事件

当一个EventEmitter实例发生错误时,会抛出一个error事件。如果这个实例没有任何error事件监听函数,那么,会抛出错误并终止node进程。

为了防止node的进程中断,可以注册process object's uncaughtException event事件的监听者。

最佳实践,EventEmitter实例监听error事件.

newListener事件和removeListener事件

在注册一个事件监听函数之前或者移除一个事件监听函数之后,EventEmitter实例会emit newListener事件和removeListener事件

一个事件的最大监听者数

默认情况下,一个事件的最大监听者数为10,可以通过 emitter.setMaxListeners(n)  方法设置,也可以利用EventEmitter.defaultMaxListeners 特性来设置


D:\projectcode\jijianguanli\hussar-front>yarn install yarn install v1.22.22 info No lockfile found. [1/4] Resolving packages... warning glob@7.2.3: Glob versions prior to v9 are no longer supported warning glob > inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerfu l. warning vue-loader > @vue/component-compiler-utils > consolidate@0.15.1: Please upgrade to consolidate v1.0.0+ as it has been modernized with several long-awaited fixes implemented. Maintenance is supported by Forward Email at https:// forwardemail.net ; follow/watch https://github.com/ladjs/consolidate for updates and release changelog warning @wchbrad/vue-easy-tree > vue@2.6.11: Vue 2 has reached EOL and is no longer actively maintained. See https://v2.vuejs.org/eol/ for more details. warning Resolution field "glob@7.2.3" is incompatible with requested version "glob@^10.3.3" warning async-validator > babel-runtime > core-js@2.6.12: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions coul d cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js. error Error: https://registry.npmmirror.com/@hussar%2fapp-core-components: Not found at params.callback [as _callback] (D:\nodejs14.14\node_global\node_modules\yarn\lib\cli.js:66680:18) at self.callback (D:\nodejs14.14\node_global\node_modules\yarn\lib\cli.js:141410:22) at Request.emit (node:events:517:28) at Request.<anonymous> (D:\nodejs14.14\node_global\node_modules\yarn\lib\cli.js:142382:10) at Request.emit (node:events:517:28) at IncomingMessage.<anonymous> (D:\nodejs14.14\node_global\node_modules\yarn\lib\cli.js:142304:12) at Object.onceWrapper (node:events:631:28) at IncomingMessage.emit (node:events:529:35) at endReadableNT (node:internal/streams/readable:1400:12) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值