What is Non-Blocking IO in Node.js: Explanation and Example
non-blocking IO means the program can start an input/output operation and continue running without waiting for it to finish. This lets Node.js handle many tasks at once efficiently, improving performance especially for web servers.How It Works
Imagine you are cooking dinner and waiting for water to boil. Instead of standing by the stove doing nothing, you prepare the salad while the water heats up. This is how non-blocking IO works in Node.js. When Node.js starts a task like reading a file or fetching data from the internet, it doesn't wait for the task to finish. Instead, it moves on to other tasks.
Node.js uses an event loop to keep track of these tasks. When the IO operation finishes, the event loop tells Node.js to handle the result. This way, Node.js can manage many IO operations at the same time without getting stuck waiting for one to complete.
Example
This example shows reading a file without blocking the program. Node.js starts reading the file and immediately prints a message. When the file is done reading, it prints the file content.
import { readFile } from 'fs/promises'; console.log('Start reading file'); async function read() { const data = await readFile('example.txt', 'utf8'); console.log('File content:', data); } read(); console.log('Continue with other work');
When to Use
Use non-blocking IO in Node.js when you want your app to handle many tasks at once without waiting. This is especially useful for web servers that serve many users, APIs that fetch data from databases, or apps that read and write files while still responding quickly.
Non-blocking IO helps keep your app fast and responsive, even under heavy load.
Key Points
- Non-blocking IO lets Node.js start IO tasks and continue running other code.
- The event loop manages when IO tasks finish and triggers their results.
- This approach improves performance for apps handling many simultaneous operations.
- It is ideal for servers, APIs, and apps needing high responsiveness.