node.js - event loop

Node.js is a single-process single-threaded application, but because of the asynchronous execution callback interface provided by the V8 engine, through which a large amount of concurrency can be handled, the performance is very high.

Almost every API in Node.js supports callback functions.

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

Node.js single-threading is similar to entering a while(true) event loop until no event observers exit, each asynchronous event generates an event observer, and calls the callback function if an event occurs.

event driver

Node.js uses an event-driven model. When the web server receives a request, it closes it and processes it, and then serves the next web request.

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

This model is very efficient and scalable because the webserver is always accepting requests without waiting for any read or write operations. (This is also called non-blocking IO or event-driven IO)

In the event-driven model, a main loop is generated to listen for events, and a callback function is triggered when an event is detected.

The entire event-driven process is implemented in this way, which is very concise. Somewhat similar to the observer pattern, an event is equivalent to a subject (Subject), and all handlers registered to this event are equivalent to observers (Observer).

Node.js has multiple built-in events. We can bind and listen to events by introducing the events module and instantiating the EventEmitter class, as shown in the following example:

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

The following program binds event handlers: 

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

 We can trigger events programmatically:

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

example 

Create the main.js file, the code is 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("程序执行完毕。");

 Next let's execute the above code:

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

 How do Node applications work?

In a Node application, functions that perform asynchronous operations take a callback function as the last argument, and the callback function receives an error object as the first argument.

Next, let's revisit the previous example and create an input.txt with the following content:

csdn地址:https://blog.csdn.net/jewels_w?type=lately

 Create a main.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("程序执行完毕");

 

In the above program, fs.readFile() is an asynchronous function for reading files. If an error occurs while reading the file, the err object will output an error message.

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

Execute the above code, the execution result is as follows:

程序执行完毕
csdn地址:https://blog.csdn.net/jewels_w?type=lately

 Next, we delete the input.txt file, and the execution result is as follows:

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

 An error message is output because the file input.txt does not exist.

Guess you like

Origin blog.csdn.net/jewels_w/article/details/130625115