Latest web development tutorials

Node.js event loop

Node.js is a single-process single-threaded applications, but supports concurrent via events and callbacks, so performance is very high.

Each Node.js API is asynchronous and runs as a separate thread, using asynchronous function calls, and concurrency.

Node.js substantially all of the event mechanism is implemented using design mode observer mode.

Node.js is similar to entering a single thread while (true) event loop until there is no exit event observer, each asynchronous event generates an event observer, if an event occurs is called the callback function.


Event-driven programming

Node.js using event-driven model, when the web server receives the request, and then put it off for processing and then to the next web service request.

When the request is completed, it is returned to the processing queue, the queue when it reaches the beginning, the result is returned to the user.

This model is very efficient scalability is very strong, because the webserver has been receiving requests without waiting for any read or write operation. (This is also known as non-blocking IO or event-driven IO)

In the event-driven model, it generates a main loop to listen for events to trigger a callback function when an event is detected.

The whole process is so event-driven to achieve, is very simple. Somewhat similar to the observer pattern, the event is equivalent to a theme (Subject), while all registered handler to this event corresponds to the observer (Observer).

Node.js has multiple built-in event, we can through the introduction of events module, and to bind and listen for events by instantiating EventEmitter class following examples:

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

The following procedure binding event handler:

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

We can program the triggering event:

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

Examples

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

Let's execute the code above:

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

How Node application work?

In Node application function performs an asynchronous operation callback function as the last parameter callback function receives the error object as the first parameter.

Let us re-look at the previous example, create a input.txt, document reads as follows:

本教程官网地址:www.w3big.com

Create main.js file, as follows:

var fs = require("fs");

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

Program above fs.readFile () is an asynchronous function is used to read the file. If an error occurs in the process of reading the file, the error err objects will output an error message.

If no errors, readFile skip output err object, the file content is output through the callback function.

Execute the code above, execution results are as follows:

程序执行完毕
本教程官网地址:www.w3big.com

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

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

Input.txt because the file does not exist, so the output of the error message.