Node.js event loop
Translation results:
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 loopsyntax
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 loopexample
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("程序执行完毕。");