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 class EventEmitter类
- Java Script Callback functions Java脚本回调函数
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:
代码扩展:
- At line no:5-6, we have imported Node JS “events” and “fs” (FileSystem) module into our application cache. 在第5-6行,我们已将Node JS“事件”和“ fs”(文件系统)模块导入到我们的应用程序缓存中。
- At line no:7, we have created an object of EventEmitter class 在第7行,我们创建了EventEmitter类的对象
- At line no:15-33, we have written JavaScript functions. We use them as Event Handler Functions. 在第15-33行,我们编写了JavaScript函数。 我们将它们用作事件处理程序函数。
- 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”事件处理函数绑定在一起。
- 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”事件处理函数绑定在一起。
- At line no:11, we have binded “finished” event with “finished” Event Handler function using on() method of EventEmitter class. 在第11行,我们使用EventEmitter类的on()方法将“完成的”事件与“完成的”事件处理函数绑定在一起。
- 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