Skip to main content

Command Palette

Search for a command to run...

Blocking vs Non-Blocking Code in Node.js

Updated
β€’3 min read
Blocking vs Non-Blocking Code in Node.js
S

Like to study,fitness freak,my looks is my first priority, hardworking person, like discipline and love to learn new thing

πŸš€ Introduction

One of the biggest reasons Node.js is fast is because of how it handles code execution.

πŸ‘‰ The key concept is:

Blocking vs Non-Blocking Code

Understanding this can completely change how you write backend applications πŸ”₯


🧠 What Is Blocking Code?

Blocking code means:

πŸ‘‰ Execution stops until the current task finishes


πŸ“¦ Example (Blocking)

const fs = require("fs");

const data = fs.readFileSync("file.txt");
console.log(data.toString());

console.log("Next task");

Output:

(File content)
Next task

πŸ‘‰ Node.js waits for file reading to complete ❌


πŸ“Š Diagram Idea: Blocking Execution

Start β†’ Read File β†’ Wait β†’ Done β†’ Next Task

🀯 Why Blocking Slows Servers

If one request blocks:

πŸ‘‰ All other requests must wait 😡

  • Poor performance

  • Slow response time

  • Bad user experience


πŸ’‘ What Is Non-Blocking Code?

Non-blocking code means:

πŸ‘‰ Execution continues without waiting for the task to finish


πŸ“¦ Example (Non-Blocking)

const fs = require("fs");

fs.readFile("file.txt", (err, data) => {
  console.log(data.toString());
});

console.log("Next task");

Output:

Next task
(File content)

πŸ‘‰ Node.js continues execution immediately βœ”οΈ


πŸ“Š Diagram Idea: Non-Blocking Execution

Start β†’ Read File β†’ Continue β†’ Next Task  
                     ↓  
                 File Done β†’ Callback

🍳 Real-Life Analogy: Waiting vs Continuing

❌ Blocking

  • Order food πŸ”

  • Wait at counter until ready


βœ… Non-Blocking

  • Order food πŸ”

  • Sit down and relax

  • Get food when ready

πŸ‘‰ Much more efficient πŸš€


βš™οΈ Async Operations in Node.js

Node.js uses async operations for:

  • File system πŸ“‚

  • Database queries πŸ—„οΈ

  • API calls 🌐

πŸ‘‰ These are handled in the background


πŸ”„ Real-World Scenario

πŸ”Ή Blocking Server

User1 β†’ Processing β†’ Done  
User2 β†’ Waiting ❌  

πŸ”Ή Non-Blocking Server

User1 β†’ Processing  
User2 β†’ Processing  
User3 β†’ Processing  

πŸ‘‰ Multiple users handled efficiently βœ”οΈ


🧠 Impact on Server Performance

Feature Blocking Non-Blocking
Execution Waits Continues
Performance Slow Fast
Scalability Low High
Use Case Simple tasks I/O operations

🧩 Conceptual Understanding

πŸ‘‰ Blocking = β€œWait and do” πŸ‘‰ Non-blocking = β€œStart and continue”


🏁 Conclusion

Node.js shines because it avoids blocking operations.

By using non-blocking code, it can:

  • Handle many requests

  • Improve performance

  • Build scalable applications


✨ Final Tip

If your server feels slow β†’ check for blocking code 😎

Blocking vs Non-Blocking Code in Node.js