Node.js is a platform built on the Chrome JavaScript runtime.

Node.js is an event-driven I/O server-side JavaScript environment based on Google's V8 engine. The V8 engine executes Javascript very quickly and has very good performance.

Node.js event loop syntax

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

Almost every API in Node.js supports callback functions.

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

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

Node.js event loop example

Create the main.js file, the code is as follows:

// 引入 events 模塊
var events = require('events');
// 創(chuàng)建 eventEmitter 對象
var eventEmitter = new events.EventEmitter();
// 創(chuàng)建事件處理程序
var connectHandler = function connected() {   console.log('連接成功。');     
// 觸發(fā) data_received 事件    
eventEmitter.emit('data_received');}
// 綁定 connection 事件處理程序
eventEmitter.on('connection', connectHandler); 
// 使用匿名函數綁定 data_received 事件
eventEmitter.on('data_received', function(){   console.log('數據接收成功。');});
// 觸發(fā) connection 事件 
eventEmitter.emit('connection');
console.log("程序執(zhí)行完畢。");