Node .js event loop

Node .js a single-process, single-threaded application, but contigies are supported through events and callbacks, so performance is very high.

Every .js node is asynchronous and runs as a stand-alone thread, called using asynchronous functions, and processed in a synth.

Node .js Basically all event mechanisms are implemented using the observer pattern in the design pattern.

Node.js A single thread is similar to entering a while (true) event loop until no event observer exits, and each asynchronous event generates an event observer that calls the callback function if an event occurs.


The event driver

Node .js use the event-driven model, and when the web server receives a request, it shuts it down, processes it, and then goes to the service for the next web request.

When the request is complete, it is put back into the processing queue, and when it reaches the beginning of the queue, the result is returned to the user.

This model is very efficient and scalable because webservers always accept requests without waiting for any reads and writes. ( This is also known as a non-blocking IO or event-driven IO)

In the event-driven model, a main loop is generated to listen for events, triggering callback functions when events are detected.

Node .js event loop

That's how the whole event-driven process is implemented, very concisely. I t's a bit like observer mode, where an event is equivalent to a subject, and all the handlers registered to the event are equivalent to observers.

Node .js has several built-in events, and we can bind and listen for events by introducing the events module and instantiated the EventEmitter class, as follows:

// 引入 events 模块
var events = require('events');
// 创建 eventEmitter 对象
var eventEmitter = new events.EventEmitter();

The following programs bind event handlers:

// 绑定事件及事件的处理程序
eventEmitter.on('eventName', eventHandler);

We can trigger an event through a program:

// 触发事件
eventEmitter.emit('eventName');

Instance

Create a main .js file, as follows:

// 引入 events 模块
var events = require('events');
// 创建 eventEmitter 对象
var eventEmitter = new events.EventEmitter();

// 创建事件处理程序
var connectHandler = function connected() {
   console.log('连接成功。');
  
   // 触发 data_received 事件 
   eventEmitter.emit('data_received');
}

// 绑定 connection 事件处理程序
eventEmitter.on('connection', connectHandler);
 
// 使用匿名函数绑定 data_received 事件
eventEmitter.on('data_received', function(){
   console.log('数据接收成功。');
});

// 触发 connection 事件 
eventEmitter.emit('connection');

console.log("程序执行完毕。");

Let's do the following code:

$ node main.js
连接成功。
数据接收成功。
程序执行完毕。

How does the Node application work?

In a Node application, a function that performs asynchronous operations uses the callback function as the last argument, and the callback function receives the wrong object as the first argument.

Let's take a look back at the previous example and create an input .txt file as follows:

W3Cschool教程官网地址:www.w3cschool.cn

Create a .js file with the following code:

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err){
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});
console.log("程序执行完毕");

Fs.readFile() in the above program is an asynchronous function used to read files. If an error occurs during reading the file, the error err object outputs an error message.

If no error occurs, readFile skips the output of the err object, and the contents of the file are output through the callback function.

The above code is executed as follows:

程序执行完毕
W3Cschool教程官网地址:www.w3cschool.cn

Next we delete the input .txt file and the results are as follows:

程序执行完毕
Error: ENOENT, open 'input.txt'

The error message .txt because the file input does not exist.