Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Event Loop

Node.js Event Loop

The event loop is the core mechanism by which Node.js handles non-blocking I/O operations, enabling a single thread to efficiently handle multiple concurrent requests.

Node.js is a single-threaded JavaScript runtime that uses the event loop to handle asynchronous operations such as file reads, network requests, and database queries.

The event loop enables Node.js to run code in a non-blocking manner, handle multiple connections, and perform asynchronous I/O operations.

The event loop allows Node.js to handle a large number of concurrent I/O operations without blocking the thread, which is the key to Node.js's efficient handling of concurrent requests.

Phases of the event loop

The event loop is divided into multiple phases, each handling specific tasks. The key phases are as follows:

The Flow of the Event Loop

Example

setTimeout

(

(

)

=>

{

  console.

log

(

'Timeout callback'

)

;

}

,

0

)

;

setImmediate

(

(

)

=>

{

  console.

log

(

'Immediate callback'

)

;

}

)

;

console.

log

(

'Main thread execution'

)

;

Output order:

Macrotasks and Microtasks

**Execution Order:** Microtasks have higher priority than macrotasks and are executed immediately after the callbacks of the current phase finish.

Example

setTimeout

(

(

)

=>

{

  console.

log

(

'Timeout callback'

)

;

}

,

0

)

;

Promise.

resolve

(

)

.

then

(

(

)

=>

{

  console.

log

(

'Promise callback'

)

;

}

)

;

console.

log

(

'Main thread execution'

)

;

Execution output:

Main thread execution
Promise callback
Timeout callback

process.nextTick()

process.nextTick() executes microtasks after the current operation ends and before the next phase begins, with higher priority than Promise.

Example

process.

nextTick

(

(

)

=>

{

  console.

log

(

'Next tick callback'

)

;

}

)

;

console.

log

(

'Main thread execution'

)

;

Output:


Main thread execution
Next tick callback

Event-Driven Programs

In Node.js, event-driven programming is mainly implemented through the EventEmitter class.

EventEmitter is a built-in class located in the events module. By inheriting from EventEmitter, you can create your own event emitters and register and trigger events.

Through this mechanism, Node.js can efficiently handle asynchronous tasks and achieve concurrent processing even in a single-threaded environment.

The entire event-driven flow is implemented this way, very concisely. It is somewhat similar to the observer pattern: an event corresponds to a Subject, and all handler functions registered to that event correspond to Observers.

Basic Concepts:

The Event-Driven Flow:

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


// import events module
var events = require('events');
// Create eventEmitter object
var eventEmitter = new events.EventEmitter();

The following program binds event handlers:


// Bind events and their handlers
eventEmitter.on('eventName', eventHandler);

We can trigger events through the program:


// Trigger event
eventEmitter.emit('eventName');

Example

Create a hello.js file with the following code:

Example 1

const

EventEmitter

=

require

(

'events'

)

;

const

myEmitter

=

new

EventEmitter

(

)

;

// Register event handlers

myEmitter.

on

(

'greet'

,

(

)

=>

{

  console.

log

(

'Hello, world!'

)

;

}

)

;

// Trigger an event

myEmitter.

emit

(

'greet'

)

;

Output:


Hello, world!

Create a main.js file with the following code:

Example 2

//

Import the events module

var

events

=

require

(

'

events

'

)

;

//

Create an eventEmitter object

var

eventEmitter

=

new

events

.

EventEmitter

(

)

;

//

Create event handlers

var

connectHandler

=

function

connected

(

)

{

console

.

log

(

'

Connection successful.

'

)

;

//

Trigger the data_received event

eventEmitter

.

emit

(

'

data_received

'

)

;

}

//

Bind the connection event handler

eventEmitter

.

on

(

'

connection

'

,

connectHandler

)

;

//

Bind the data_received event using an anonymous function

eventEmitter

.

on

(

'

data_received

'

,

function

(

)

{

console

.

log

(

'

Data received successfully.

'

)

;

}

)

;

//

Trigger the connection event

eventEmitter

.

emit

(

'

connection

'

)

;

console

.

log

(

"

Program execution complete.

"

)

;

Next, let's execute the above code:


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

How Does a Node Application Work?

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

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


Runoob Tutorial官网地址:www.runoob.com

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 used to read a file. If an error occurs during the file read, the err object outputs the error information.

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

After executing the above code, the result is as follows:


程序执行完毕
Runoob Tutorial官网地址:www.runoob.com

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


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

Because the file input.txt does not exist, an error message is output.