What is Non-blocking I/O?
1. Definition
Non-blocking I/O is a method where operations like file reading, database calls, or network requests do not block the execution of the program. Instead, the program continues running and handles the result later using callbacks, promises, or async/await.
2. Key Idea
- Execution does not wait for task completion
- Other code continues to run
- Result is handled later
- Uses asynchronous programming
3. How it Works
- Request is sent for a task (e.g., file read)
- Task is handled in background (thread pool)
- Main thread continues execution
- When task is done, callback is executed
4. Example
const fs = require("fs");
console.log("Start");
fs.readFile("file.txt", "utf-8", (err, data) => {
console.log("File read completed");
});
console.log("End");👉 Output:
Start End File read completed
👉 File reading happens in background, so execution does not stop.
5. Blocking vs Non-blocking
- Blocking: Code waits until task is completed
- Non-blocking: Code continues execution without waiting
- Blocking: Slower performance
- Non-blocking: Faster and scalable
6. Why This is Important
- Handles multiple users efficiently
- Improves performance
- Prevents application freezing
- Core concept of Node.js
7. Advantages
- High scalability
- Better resource utilization
- Fast response handling
8. Disadvantages
- Code can be harder to understand
- Callback hell if not managed properly
Interview Points
- Non-blocking I/O does not stop execution
- Uses callbacks, promises, async/await
- Core feature of Node.js
- Improves scalability and performance