eventemitter

We have already discussed in previous posts about Node JS Architecture. Node JS follows Event Driven Single Thread Approach. Please go through my previous posts: “Node JS Single Threaded Event Loop Architecture” and “Node JS FileSystem IO Package” because we are going to use FS module knowledge in this Events module examples.

我们已经在以前的文章中讨论过Node JS Architecture。 节点JS遵循事件驱动单线程方法。 请仔细阅读我以前的文章: “ Node JS单线程事件循环体系结构”和“ Node JS FileSystem IO程序包”,因为我们将在此“事件”模块示例中使用FS模块知识。

We will discuss Node JS Platform “events” module and EventEmitter class with some suitable examples in this post.

我们将在本文中与一些合适的示例一起讨论Node JS Platform的“事件”模块和EventEmitter类。

节点JS事件模块 (Node JS Events Module)

Node JS Platform follows Events Driven Programming model. It follows Observer Design Pattern to handle events. In Node JS applications, every operation generates an event. And it has some Event Handlers to handle those events.

Node JS平台遵循事件驱动编程模型。 它遵循观察者设计模式来处理事件。 在Node JS应用程序中,每个操作都会生成一个事件。 它具有一些事件处理程序来处理这些事件。

For example:-
Take Node JS FS(File System) Module. When Node JS application try to open a file, then it generates an event. If it finishes reading data from a file using ReadStream, then it generates another event. If it finishes writing data to a file using WriteStream, then it generates another event. Like this for every action in Node JS Application, it generates an event.

例如:-
以Node JS FS(文件系统)模块为例。 当Node JS应用程序尝试打开文件时,它将生成一个事件。 如果完成使用ReadStream从文件中读取数据,则它将生成另一个事件。 如果完成使用WriteStream将数据写入文件中,则它将生成另一个事件。 这样,Node JS应用程序中的每个动作都会生成一个事件。

Then, Who is responsible to generate those events? Who is responsible to handle those events? We will discuss all these questions in details soon in this post.

那么,谁负责产生这些事件呢? 谁负责处理这些事件? 我们将在本文中很快详细讨论所有这些问题。

Like some Node modules for example “npm”, “fs” etc., Node JS “events” module is also part of basic Node JS Platform. We don’t need to do anything to setup Node JS Events module.

与某些Node模块(例如“ npm”,“ fs”等)一样,Node JS“事件”模块也是基本Node JS平台的一部分。 我们无需执行任何操作即可设置Node JS Events模块。

Why Node JS is faster?
Compared to other technologies, Node JS applications provide very high performance because of this Event-Driven Programming model.

为什么Node JS更快?
与其他技术相比,Node JS应用程序由于此事件驱动的编程模型而提供了非常高的性能。

What is EventEmitter?
As of today, Node JS “events” module has one and only one class to handle events: EventEmitter class. It contains all required functions to take care of generating events.

什么是EventEmitter?
到目前为止,Node JS“事件”模块只有一个类可以处理事件:EventEmitter类。 它包含所有必需的功能,用于处理事件。

Who is responsible to generate events in Node JS Application ?
EventEmitter class is responsible to generate events. Generating events is also known as Emitting. That’s why this class name is EventEmitter as it emits events in Node JS Platform.

谁负责在Node JS应用程序中生成事件?
EventEmitter类负责生成事件。 生成事件也称为发射。 这就是为什么此类名称为EventEmitter的原因,因为它在Node JS Platform中发出事件。

After generating events, it places all events into Event Queue(Refer “Node JS Single Threaded Event Loop Architecture” posts about the usage of Event Queue). Then Event Loop picks-up events one by one from Event Queue and process them accordingly.

生成事件后,它将所有事件放入事件队列(请参阅“ Node JS单线程事件循环体系结构”中有关事件队列用法的文章)。 然后,事件循环从事件队列中逐个拾取事件并进行相应处理。

Who is responsible to handle events in Node JS Application ?
Node JS Platform uses the following two components to take of events.

谁负责处理Node JS Application中的事件?
Node JS平台使用以下两个组件来处理事件。

  • EventEmitter classEventEmitter类
  • Java Script Callback functionsJava脚本回调函数

EventEmitter class is responsible to generate events and Java Script Callback functions are responsible to handle them.

EventEmitter类负责生成事件,而Java Script Callback函数负责处理事件。

We can explain this complete process with a diagram as shown below:

我们可以用如下图来解释这个完整的过程:

  • When Node JS application starts or ends an operation, EventEmitter class generates events and places them into Event Queue.当Node JS应用程序开始或结束操作时,EventEmitter类将生成事件并将其放入事件队列。
  • Event Queue maintains a Queue of Events.事件队列维护事件队列。
  • Event Loop continuously waits for new events in Event Queue. When it finds events in Event Queue, it pulls them and try to process them. If they require IO Blocking operations or long waiting tasks, then assigns respective Event Handlers to handle them.事件循环持续等待事件队列中的新事件。 当它在事件队列中找到事件时,将其拉出并尝试对其进行处理。 如果它们需要IO阻止操作或长时间等待的任务,则分配相应的事件处理程序来处理它们。
  • Event Handlers are JavaScript Asynchronous Callback Functions. They are responsible to handle events and return results to Event Loop.事件处理程序是JavaScript异步回调函数。 他们负责处理事件并将结果返回到事件循环。
  • Event Loop will prepare results and send them back to the Client.事件循环将准备结果并将其发送回客户端。

First and foremost thing to start Node JS Events programming is that import “events” module as shown below:

开始Node JS Events编程的首要任务是导入“事件”模块,如下所示:

var events = require("events");

Then use this events variable and create an object of EventEmitter class as shown below:

然后使用此事件变量并创建EventEmitter类的对象,如下所示:

var eventsEmitter = new events.EventEmitter();

EventEmitter的“ emit()”函数 (EventEmitter “emit()” function)

EventEmitter class has a “emit()” function, which is used to create an Event. It takes one parameter.

EventEmitter类具有“ emit()”函数,该函数用于创建事件。 它需要一个参数。

eventsEmitter.emit(NameOfEventToCreate);

Here, NameOfEventToCreate: we need to pass Event Name to emit() function call as String to create that Event.

在这里,NameOfEventToCreate:我们需要将事件名称作为String传递给generate()函数调用以创建该事件。

Example:-

例:-

var events = require("events");
var eventsEmitter = new events.EventEmitter();
eventsEmitter.emit("mobileon");

EventEmitter的“ on()”函数 (EventEmitter “on()” function)

EventEmitter class has a “on()” function, which is used to bind an Event with an Event Handler JavaScript Function. It takes two parameters.

EventEmitter类具有一个“ on()”函数,该函数用于将事件与事件处理程序JavaScript函数绑定。 它有两个参数。

eventsEmitter.on(NameOfEventToBind, EventHandlerFuction);

Here, NameOfEventToBind: We need to pass Event Name a to on() function call as String to bind that event to given Event Handler JavaScript Function.
and EventHandlerFuction: Given Event Handler JavaScript Function to handle that event. It may be an anonymous JavaScript function or Plain JavaScript function.

在这里,NameOfEventToBind:我们需要将事件名称a作为字符串传递给on()函数调用,以将该事件绑定到给定的事件处理程序JavaScript函数。
和EventHandlerFuction:给定的事件处理程序JavaScript函数来处理该事件。 它可以是匿名JavaScript函数或纯JavaScript函数。

Example:-
This example is using anonymous JavaScript function as Event Handler.

例:-
本示例将匿名JavaScript函数用作事件处理程序。

var events = require("events");
var eventsEmitter = new events.EventEmitter();
eventsEmitter.emit("mobileon",function(data){console.log(data);
});
eventsEmitter.emit("mobileon");

We can also use Plain JavaScript function as Event Handler as shown below:

我们还可以将Plain JavaScript函数用作事件处理程序,如下所示:

var events = require("events");
var eventsEmitter = new events.EventEmitter();
eventsEmitter.emit("mobileon",mobileOnHadler);
eventsEmitter.emit("mobileon");function mobileOnHadler(data){console.log(data);
}

With this knowledge about EventEmitter class, we will develop a real-time simple example to see how Node JS handles events.

有了有关EventEmitter类的知识,我们将开发一个实时的简单示例,以了解Node JS如何处理事件。

节点JS事件示例:- (Node JS Events Example:-)

This example demonstrates How to raise Events while Reading a File form FileSyste in Node JS Platform.

本示例演示了如何在Node JS Platform中读取文件形式FileSyste时引发事件。

  • Create Node JS Project using Enide 2014 Studio IDE使用Enide 2014 Studio IDE创建Node JS项目
  • Copy from my previous example or Create package.json file and modify it with the following content从我之前的示例中复制或创建package.json文件,并使用以下内容对其进行修改
  • package.json

    package.json

{"name": "events","version": "1.0.0","description": "events example","main": "events","author": "JournalDEV","engines":{"node":"*"}}
  • Create a text file “JournalDEV.txt” with the following content. We are going to use this file to test Node Js events.创建具有以下内容的文本文件“ JournalDEV.txt”。 我们将使用此文件测试Node Js事件。
  • JournalDEV.txt

    JournalDEV.txt

    Dear, JournalDEV Readers.
    Thank You for your support.
  • Create a JavaScript file with the following content创建具有以下内容JavaScript文件
  • events.js

    events.js

    /*** JournalDEV  * Nodes Events Demo*/
    var events = require("events");
    var fs = require('fs');
    var eventsEmitter = new events.EventEmitter();eventsEmitter.on('read',readFileContent);
    eventsEmitter.on('display',displayFileContent);
    eventsEmitter.on('finished',finished);
    eventsEmitter.emit('read','JournalDEV.txt');function readFileContent(fileName){console.log("Reading " + fileName + " file started:");fs.readFile(fileName, 'utf8', readFile);
    }function  displayFileContent(data){console.log("File Data:");console.log(data);eventsEmitter.emit('finished');
    }function finished(){console.log("Reading and Printing File content job is done successfully.");
    }function readFile(err,data,fileName) {console.log("Reading " + fileName + " file done successfully.");eventsEmitter.emit('display',data);
    }

    Code exaplanation:

    代码扩展:

    1. At line no:5-6, we have imported Node JS “events” and “fs” (FileSystem) module into our application cache.在第5-6行,我们已将Node JS“事件”和“ fs”(文件系统)模块导入到我们的应用程序缓存中。
    2. At line no:7, we have created an object of EventEmitter class在第7行,我们创建了EventEmitter类的对象
    3. At line no:15-33, we have written JavaScript functions. We use them as Event Handler Functions.在第15-33行,我们编写了JavaScript函数。 我们将它们用作事件处理程序函数。
    4. At line no:9, we have binded “read” event with “readFileContent” Event Handler function using on() method of EventEmitter class.在第9行,我们使用EventEmitter类的on()方法将“ read”事件与“ readFileContent”事件处理函数绑定在一起。
    5. At line no:10, we have binded “display” event with “displayFileContent” Event Handler function using on() method of EventEmitter class.在第10行,我们使用EventEmitter类的on()方法将“ display”事件与“ displayFileContent”事件处理函数绑定在一起。
    6. At line no:11, we have binded “finished” event with “finished” Event Handler function using on() method of EventEmitter class.在第11行,我们使用EventEmitter类的on()方法将“完成的”事件与“完成的”事件处理函数绑定在一起。
    7. At line no:12, we have raised a “read” event by passing filename “JournalDEV.txt” as input using emit() method of EventEmitter class.在第12行,我们通过使用EventEmitter类的emit()方法传递文件名“ JournalDEV.txt”作为输入来引发“读取”事件。
  • Final Project structure will looks like this:最终项目的结构如下所示:
  • NOTE:-Please ignore “events2.js” file. That is back file for my future reference.

    注意:-请忽略“ events2.js”文件。 那是后备文件,供我将来参考。

  • Run this JavaScript file and observe the output at Enide 2014 Studio IDE Console运行此JavaScript文件,并观察Enide 2014 Studio IDE控制台的输出
  • By observing this output, we are successfully raised some events while reading a file and handled them propertly.

    通过观察此输出,我们在读取文件并正确处理它们时成功引发了一些事件。

    That’s it about Node JS Events Module. If you have any questions,please drop me a comment.

    就是关于Node JS Events Module的事情。 如果您有任何疑问,请给我评论。

    翻译自: https://www.journaldev.com/7991/node-js-events-module-and-eventemitter

    eventemitter

eventemitter_节点JS事件模块和EventEmitter相关推荐

  1. node.js 事件循环

    node.js是单线程的应用程序,但是他可能通过event和callback来支持并发.所有的node.js都是单线程的,也是异步的,他们使用调用异步函数来维持高并发.Node使用观察者模式.Node ...

  2. 工作流 节点子线程_节点JS体系结构–单线程事件循环

    工作流 节点子线程 Today we will look into Node JS Architecture and Single Threaded Event Loop model. In our ...

  3. js动态添加html元素绑定事件,JS实现动态添加DOM节点和事件的方法示例

    本文实例讲述了JS实现动态添加DOM节点和事件的方法.分享给大家供大家参考,具体如下: 运行效果图如下: 完整实例代码如下: /p> "http://www.w3.org/TR/xht ...

  4. 如何构建自定义 Node.js 事件发射器

    事件是具有软件或硬件意义的动作. 它们是由于用户活动(例如鼠标单击或击键)或直接来自系统(例如错误或通知)而发出的. JavaScript 语言使我们能够通过在事件处理程序中运行代码来响应事件. 由于 ...

  5. jquery源码分析(七)——事件模块 event(二)

    上一章节探讨了事件的一些概念,接下来看下jQuery的事件模块. jQuery对事件的绑定分别有几个API:.bind()/.live()/.delegate()/.on()/click(), 不管是 ...

  6. node.js中模块_在Node.js中需要模块:您需要知道的一切

    node.js中模块 by Samer Buna 通过Samer Buna 在Node.js中需要模块:您需要知道的一切 (Requiring modules in Node.js: Everythi ...

  7. Linux事件循环阻塞,深入浅析Node.js 事件循环、定时器和process.nextTick()

    什么是事件循环 尽管JavaScript是单线程的,但通过尽可能将操作放到系统内核执行,事件循环允许Node.js执行非阻塞I/O操作. 由于现代大多数内核都是多线程的,因此它们可以处理在后台执行的多 ...

  8. Node.js Domain 模块

    Node.js 工具模块 Node.js Domain(域) 简化异步代码的异常处理,可以捕捉处理try catch无法捕捉的异常.引入 Domain 模块 语法格式如下: var domain = ...

  9. 高精度事件计时器怎么关闭_Node.js 事件循环

    什么是事件循环 Node.js 是单进程单线程应用程序,但是因为 V8 引擎提供的异步执行回调接口,通过这些接口可以处理大量的并发,所以性能非常高. 事件循环能让 Node.js 执行非阻塞 I/O ...

最新文章

  1. [置顶] 面向业务开发应用
  2. 算法_棋盘型高维动态规划
  3. Matlab R2018a 64位安装教程
  4. Java源码详解二:HashMap源码分析--openjdk java 11源码
  5. PHP设计模式 -- 策略模式
  6. 实现BX的内容加上123 并把和送到寄存器AX
  7. 设置框开始隐藏状态html5,小猿圈分享HTML5中form如何关闭自动完成功能的方法
  8. HTTPS加密传输过程
  9. hdu 5229 找规律
  10. 【MediaSoup】UDPSOCKET recv数据到rtcp包解析
  11. es6 7 8 9 10特性归纳
  12. ps动作保存不覆盖原文件_Photoshop从入门到精通:图像的基本操作,新建打开保存关闭文件...
  13. 我们到底是万物之灵? 还是另一种昆虫?
  14. wps excel 表格粘贴到 word 删除首行缩进
  15. Three.js 粒子系统动画与发光材质——利用HTML5画布绘制
  16. 基于腾讯云搭建属于自己的Fiora聊天室
  17. html5生成excel,H5纯前端生成Excel表格
  18. 移动端vue仿朋友圈项目总结
  19. Git--SSH登录
  20. 软件过程与项目管理-西安电子科技大学

热门文章

  1. [学习笔记]C语言深度剖析
  2. 一封写给2009年自己的信
  3. [转载] Python - filter()用法
  4. one list to muti list
  5. python globle用法
  6. Spring Data 开发环境搭建(二)
  7. 【pwnable.kr】passcode
  8. Confluence自启动脚本
  9. [转载] AUML——FIPA Modeling Technical Committee
  10. c++时间函数及转换