Event Loop and Non-Blocking I/O in Node.js
Node.js uses an event loop to coordinate JavaScript execution, asynchronous callbacks, timers, and I/O operations. Non-blocking I/O allows Node.js to continue processing other work while waiting for operations such as file access or network communication.
1. What is the Event Loop?
The event loop is a mechanism used by Node.js to process scheduled callbacks and coordinate asynchronous operations. It helps Node.js handle many I/O operations without waiting synchronously for each operation to finish.
Imagine Samadhan is working on a project at CIIT Training Institute. He asks Pradnya to fetch a course report. While the report is being prepared, Samadhan can continue other work instead of waiting idle. Node.js follows a similar idea when handling asynchronous I/O.
2. Why Do We Need the Event Loop?
Consider a program that needs to read a file and then display another message. If the program uses synchronous file reading, JavaScript execution waits until the file read completes. With asynchronous file reading, the program can continue executing other statements.
| Blocking Operation | Non-Blocking Operation |
|---|---|
| The current JavaScript execution waits for the operation to finish. | The operation can proceed asynchronously while JavaScript continues with other work. |
| Can delay other work on the same JavaScript thread. | Helps the application remain responsive during I/O. |
Example: readFileSync(). |
Example: readFile() with a callback. |
3. Event Loop Architecture
Node.js executes JavaScript on its main thread by default. Its runtime coordinates timers, I/O completion, and callbacks. Some operations use operating-system facilities or the libuv thread pool.
4. Synchronous Code Example
Synchronous statements execute in order. Each statement completes before the next statement starts.
console.log("Samadhan started.");
console.log("Pradnya is preparing the report.");
console.log("Samadhan continues the next task.");
Output
Samadhan started. Pradnya is preparing the report. Samadhan continues the next task.
Explanation
- The first statement displays the starting message.
- The second statement executes next.
- The third statement executes after the second statement finishes.
- No asynchronous operation is scheduled in this example.
5. Non-Blocking Execution Example
The following example uses setTimeout() to schedule a
callback. JavaScript continues executing the remaining statement
without waiting for the timer.
console.log("Samadhan started.");
setTimeout(() => {
console.log("Pradnya's report is ready.");
}, 2000);
console.log("Samadhan continues working.");
Output
Samadhan started. Samadhan continues working. Pradnya's report is ready.The last message is scheduled after approximately two seconds.
Explanation
- The first message is displayed immediately.
setTimeout()schedules the callback.- The next statement executes without waiting for the timer.
- When the timer expires, the callback becomes eligible to run.
- The event loop processes the callback when JavaScript can execute it.
6. How the Event Loop Works
7. Non-Blocking I/O Using the File System
Node.js provides the fs module for working with files.
The asynchronous fs.readFile() method allows the program
to continue executing while the file is being read.
course.txt in the same directory
from which the Node.js script is run, and put
Welcome to CIIT Training Institute! inside it.
const fs = require("fs");
console.log("Samadhan started reading the course file.");
fs.readFile("course.txt", "utf8", (error, data) => {
if (error) {
console.log("Error reading file:", error.message);
return;
}
console.log("File content:", data);
});
console.log("Samadhan can do other work while the file is read.");
Possible Output
Samadhan started reading the course file. Samadhan can do other work while the file is read. File content: Welcome to CIIT Training Institute!
The file callback normally runs after the synchronous statements shown here. Actual completion time depends on the file system and runtime.
Explanation
require("fs")imports Node.js file-system functions.fs.readFile()requests an asynchronous file read.- The callback receives an error or the file data.
- The next
console.log()can run while the file read is pending. - The error check prevents the program from trying to use data when the read fails.
8. Event Loop Phases in Node.js
Node.js organizes many callback operations into event loop phases. These phases help the runtime process different categories of work.
| Phase | Purpose |
|---|---|
| Timers | Processes eligible callbacks scheduled by functions such as setTimeout() and setInterval(). |
| Pending Callbacks | Processes certain system-level callbacks deferred to this phase. |
| Idle / Prepare | Internal work performed by the runtime. |
| Poll | Processes many I/O callbacks and may wait for I/O when appropriate. |
| Check | Processes callbacks scheduled using setImmediate(). |
| Close Callbacks | Processes certain close events, such as a socket closing. |
process.nextTick() are handled
through their respective queues and scheduling rules, rather than
being ordinary event loop phases in this table. Exact scheduling
behavior can depend on the Node.js version and execution context.
9. What is Blocking Code?
Blocking code prevents the JavaScript thread from executing other JavaScript while the blocking operation is running. Long-running synchronous work can delay timers, I/O callbacks, and other requests.
const fs = require("fs");
console.log("Samadhan started.");
try {
const data = fs.readFileSync("course.txt", "utf8");
console.log("File content:", data);
} catch (error) {
console.log("Error reading file:", error.message);
}
console.log("Samadhan continues after the file read.");
Execution Order
Samadhan started. File content: Welcome to CIIT Training Institute! Samadhan continues after the file read.This output assumes course.txt exists and contains the example text.
Unlike fs.readFile(), fs.readFileSync()
does not return control to the next statement until the file read
completes or fails.
10. Blocking vs Non-Blocking I/O
| Blocking I/O | Non-Blocking I/O |
|---|---|
| Waits for the operation to complete before continuing. | Allows JavaScript to continue while the operation is pending. |
| Can delay other work on the same JavaScript thread. | Can improve responsiveness when waiting for I/O. |
Example: fs.readFileSync(). |
Example: fs.readFile(). |
| Useful when synchronous behavior is specifically needed. | Often preferred for server applications handling concurrent I/O. |
11. Common Mistakes
| Mistake | Correct Understanding |
|---|---|
| Assuming asynchronous callbacks execute immediately. | Callbacks run when they become eligible and the runtime can process them. |
| Assuming a timer always executes at the exact delay. | The specified delay is not a guarantee of exact execution time. |
| Using synchronous I/O for every file operation in a server. | Consider asynchronous I/O when the application should continue handling other work. |
| Assuming Node.js never uses threads. | Node.js can use operating-system facilities and the libuv thread pool for certain operations. |
| Writing long-running CPU-heavy code on the main JavaScript thread. | Consider worker threads or other suitable approaches for CPU-intensive tasks. |
12. Important Points to Remember
- The event loop coordinates scheduled callbacks and asynchronous work.
- Non-blocking I/O allows JavaScript to continue while I/O is pending.
- Synchronous operations execute before the next statement can proceed.
- Asynchronous operations may complete later and schedule callbacks.
- Node.js has event loop phases for different categories of callbacks.
- Long-running synchronous code can block the main JavaScript thread.
- Node.js uses runtime and operating-system facilities to support asynchronous I/O.
Summary
In this lesson, we learned about the Node.js event loop, non-blocking I/O, synchronous and asynchronous execution, file-system examples, event loop phases, and blocking code. The examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate how Node.js can continue executing work while asynchronous operations are pending.