Home > Web Front-end > JS Tutorial > Node.js event loop tutorial

Node.js event loop tutorial

巴扎黑
Release: 2017-08-08 10:35:25
Original
1721 people have browsed it

This article mainly introduces the detailed explanation and examples of Node.js event loop. Node.js has multiple built-in events. We can bind and monitor events by introducing the events module and instantiating the EventEmitter class. Friends in need can refer to

Node.js event loop details and examples

  • Node.js is a single-process single-thread application. But it supports concurrency through events and callbacks, so the performance is very high.

  • Every API in Node.js is asynchronous and runs as a separate thread, uses asynchronous function calls, and handles concurrency.

  • 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 Just call the callback function.

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


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

// 创建事件处理程序
var connectHandler = function connected() {
  console.log(1);

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

// 绑定 connection 事件处理程序
eventEmitter.on('connection', connectHandler);

// 使用匿名函数绑定 data_received 事件
eventEmitter.on('data_received', function(){
  console.log(2);
});

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

console.log(3);
Copy after login

In a Node application, the function that performs an asynchronous operation takes the callback function as the last parameter, and the callback function receives the error object as the first parameter.


var fs = require("fs")
fs.readFile('input.txt',function(err,data){
if(err)
  console.log(err)
else
  console.log(data.toString())
})
console.log("程序执行完成")
Copy after login

The above is the detailed content of Node.js event loop tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template