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:
- Timers: Before executing
setTimeout()andsetInterval()callbacks. - I/O Callbacks: Handle some deferred I/O callbacks.
- Idle, prepare: Used internally, not common.
- Poll: Retrieve new I/O events and execute I/O-related callbacks.
- Check: Before executing
setImmediate()callbacks. - Close Callbacks: Handle close callbacks, such as
socket.on('close', ...)。
The Flow of the Event Loop
- Tasks Enter the Event Loop Queue。
- The event loop processes tasks in phase order, and each phase has its own callback queue.
- The event loop waits for new events in the
pollphase; if there are no events, it checks the callbacks of other phases. - If both the
setImmediate()andsetTimeout()both exist,setImmediate()incheckthe phase runs first, whilesetTimeout()intimersthe phase runs.
Example
setTimeout
(
(
)
=>
{
console.
log
(
'Timeout callback'
)
;
}
,
0
)
;
setImmediate
(
(
)
=>
{
console.
log
(
'Immediate callback'
)
;
}
)
;
console.
log
(
'Main thread execution'
)
;
Output order:
Main thread executionis printed first.setImmediate()andsetTimeout()The execution order depends on the current state of the event loop; generallysetImmediate()executes first.
Macrotasks and Microtasks
- Macrotasks:
setTimeout、setInterval、setImmediate, I/O operations, etc. - Microtasks:
process.nextTick、Promise.then。
**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:
- Events: An action or state change that occurs in a program, such as a file read completing or an HTTP request arriving.
- Event Emitter:
EventEmitteris a built-in module of Node.js used to emit and listen for events. - Event handlers: A callback function associated with an event, invoked when the event occurs.
The Event-Driven Flow:
- Registering Events: In a program, through
EventEmitterinstances register events and their corresponding handlers. - Trigger events: When a specified event occurs,
EventEmittertriggers that event. - Handling Events: The event loop schedules the corresponding callback function to execute the task.
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.