What is Event Loop in Node.js: Explanation and Example
event loop in Node.js is a mechanism that allows Node to perform non-blocking operations by offloading tasks to the system kernel and processing callbacks asynchronously. It continuously checks for tasks, executes them, and manages asynchronous events without stopping the main program flow.How It Works
Think of the event loop as a friendly traffic controller for your Node.js program. It keeps an eye on a queue of tasks waiting to be done and decides which one to run next. Instead of waiting for a task like reading a file or fetching data from the internet to finish, Node.js sends that task off to the system and keeps working on other things.
When the task is done, the system tells the event loop, which then picks up the result and runs the related callback function. This way, your program never stops or waits unnecessarily, making it very efficient for handling many tasks at once.
Example
This example shows how Node.js uses the event loop to handle a timer and a file read operation without blocking the main program.
import { readFile } from 'fs/promises'; console.log('Start'); setTimeout(() => { console.log('Timer done'); }, 0); const fileRead = async () => { const data = await readFile(new URL('example.txt', import.meta.url), 'utf-8'); console.log('File content:', data.trim()); }; fileRead(); console.log('End');
When to Use
Use the event loop concept when you want your Node.js app to handle many tasks at the same time without waiting for each to finish before starting the next. This is especially useful for web servers, real-time apps, or any program that deals with lots of input/output operations like reading files, accessing databases, or calling APIs.
By relying on the event loop, your app stays fast and responsive even under heavy load.
Key Points
- The event loop lets Node.js do many things at once without blocking.
- It manages callbacks from asynchronous operations like timers, file reads, and network requests.
- Understanding the event loop helps you write efficient, non-blocking code.
- It is central to Node.js’s ability to handle high concurrency with a single thread.