Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Difference between Asynchronous and Non-blocking
Next article icon

Blocking and Non-Blocking in NodeJS

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In NodeJS, blocking and non-blocking are two ways of writing code. Blocking code stops everything else until it's finished, while non-blocking code lets other things happen while it's waiting. This difference is key to understanding how NodeJS works and writing fast, efficient applications.

What is Blocking?

Blocking in NodeJS means that when your code runs a task, it stops and waits for that task to completely finish before moving on to the next thing. It's like reading a book one word at a time, never skipping ahead.

  • The program waits patiently for the current operation to finish.
  • No other code can run until that operation is done.
JavaScript
function myFunction() {
    console.log("Starting a task...");
    // Simulate a long-running task (blocking)
    let sum = 0;
    for (let i = 0; i < 1000000000; i++) { // A big loop!
        sum += i;
    }
    console.log("Task finished!");
    return sum;
}

console.log("Before the function call");
let result = myFunction(); 
console.log("After the function call");
console.log("Result:", result);
  • The for loop acts like a long-running task. The program waits for it to complete.
  • The "After the function call" message doesn't print until the loop is totally done.
  • This makes the code run step-by-step, one thing at a time.

Output

blocking code output
Blocking Operation in NodeJS

What is Non-Blocking?

Non-blocking means your program can keep doing other things while a task is running in the background. It doesn't have to stop and wait for that task to finish before moving on.

  • The program doesn't wait for the current task to complete.
  • Other code can run while the task is working in the background.
JavaScript
function myFunction() {
    console.log("Starting a task...");
    // Simulate a long-running task (non-blocking) - using setTimeout
    setTimeout(() => {
        let sum = 0;
        for (let i = 0; i < 1000000000; i++) { // A big loop!
            sum += i;
        }
        console.log("Task finished!");
        console.log("Result:", sum);
    }, 0); // The 0 delay makes it asynchronous
}

console.log("Before the function call");
myFunction(); // The program doesn't wait here
console.log("After the function call");
  • The setTimeout makes the big loop run in the background. The program doesn't stop.
  • "After the function call" prints before "Task finished!" because the loop runs later.
  • This lets the program do multiple things "at the same time."

Output

Non-Blocking  output
Non Blocking Operation in NodeJS

Difference Between Blocking and Non-Blocking

Here's a table which shows the key differences between blocking and non-blocking operations

FeatureBlocking OperationsNon-Blocking Operations
ExecutionWaits until the operation completes.Continues immediately; operation completes later.
Thread BehaviorCurrent thread waits (is blocked).Current thread continues; operation handled separately.
Resource UsageEasier to implement but may waste resources while waiting.More complex but uses resources more efficiently.
ResponsivenessCan cause delays if operations are slow.Keeps application responsive during long operations.
Use CasesSimple tasks where waiting is acceptable.Tasks requiring high responsiveness, like user interfaces.
ComplexityEasier to implement.Requires managing callbacks or async mechanisms.
ExamplesReading a file entirely before proceeding.Starting a file read and continuing without waiting.
Error HandlingErrors handled immediately after the operation.Errors handled later, often in callbacks or error handlers.

Real-World Examples

Let's see how blocking and non-blocking I/O work with web servers. This will show why non-blocking is so much better, especially in NodeJS.

Blocking HTTP Server

A blocking server handles one request at a time. If it's busy reading a file for one user, other users have to wait.

const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
const data = fs.readFileSync('largeFile.txt', 'utf8'); // Blocking!
res.end(data);
}).listen(3000);

console.log("Server running at http://localhost:3000/");
  • fs.readFileSync is blocking. The server stops and waits until the entire largeFile.txt is read.
  • If another user tries to access the server while it's reading the file, they have to wait.

Non-Blocking HTTP Server

A non-blocking server can handle many requests at the same time. If it needs to read a file, it starts the read and then goes back to handling other requests. When the file is ready, the server is told about it and then it can send the data to the user.

const http = require('http');
const fs = require('fs');

http.createServer((req, res) => {
fs.readFile('largeFile.txt', 'utf8', (err, data) => { // Non-blocking!
if (err) {
res.writeHead(500);
res.end("Error reading file");
return;
}
res.end(data);
});
}).listen(3000);

console.log("Server running at http://localhost:3000/");
  • fs.readFile is non-blocking, allowing the server to handle other requests while the file is being read.
  • This approach is much more efficient for concurrent requests, as the server remains responsive and doesn't wait for I/O operations to complete.

How NodeJS Handles Non-Blocking I/O

NodeJS handles non-blocking I/O using

  • The Event Loop: A single thread (the event loop) manages asynchronous operations. When a task like file I/O or a network request is initiated, NodeJS delegates it and doesn't wait. The event loop continues processing other events.
  • Callbacks: When the I/O operation completes, NodeJS is notified and executes a callback function associated with that task. This callback handles the result of the operation.
  • Thread Pool: Certain tasks (like some file operations or computations) are handled by a thread pool. This prevents these tasks from blocking the event loop. The thread pool also uses callbacks to notify the event loop when a task is done.

How Concurrency and throughput is handled?

NodeJS is single-threaded, but it achieves concurrency through the event loop, which efficiently handles non-JavaScript operations, such as I/O tasks. Callback functions are sent to the event loop and executed only after other operations are completed.

  • Concurrency: The event loop manages multiple operations, ensuring non-blocking asynchronous tasks are handled efficiently.
  • Throughput: Non-blocking asynchronous operations are significantly faster than blocking synchronous ones, which helps in maximizing throughput.

Drawback of mixing Blocking and Non-Blocking Code

Combining blocking and non-blocking code can cause issues, such as operations executing before their dependencies are complete. For example, trying to print file content before it has been fully read.

  • Problem: Mixing can lead to unexpected behavior and incomplete operations.
  • Solution: Always use non-blocking code for related operations to ensure proper execution order.

Best Practices for Blocking and Non-Blocking in NodeJS

  • Prefer Non-Blocking Methods: Utilize asynchronous APIs to prevent the event loop from stalling, ensuring efficient handling of multiple operations.
  • Use Promises and Async/Await: Implement these for clearer, more manageable asynchronous code, reducing callback complexity.
  • Monitor Event Loop Lag: Regularly check for delays in the event loop to identify and address potential performance bottlenecks.

Next Article
Difference between Asynchronous and Non-blocking

A

adityapande88
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node.js-Basics
  • NodeJS-function

Similar Reads

    Non-Blocking event loop in Node.js
    Node.js operates on a single-threaded, event-driven architecture that relies heavily on non-blocking I/O operations to handle concurrent requests efficiently. This approach is enabled by its event loop mechanism, which allows Node.js to handle multiple requests concurrently without creating addition
    5 min read
    Explain the concept of non-blocking I/O in Node
    In traditional synchronous programming models, I/O operations such as reading from a file or making network requests block the execution of the program until the operation completes. This means that if there are multiple I/O operations, they are processed sequentially, leading to potential bottlenec
    3 min read
    Callbacks and Events in NodeJS
    Callbacks and events are fundamental building blocks for asynchronous programming in NodeJS. They're essential for handling operations that might take some time, ensuring your application handles asynchronous operations smoothly.Callback in NodeJSIn NodeJS, Callbacks are functions passed as argument
    3 min read
    Difference between Asynchronous and Non-blocking
    Asynchronous and non-blocking are related but distinct concepts in programming, particularly in the context of I/O operations. Asynchronous: Asynchronous refers to the ability of a program or system to perform multiple tasks simultaneously without waiting for each task to be complete before starting
    2 min read
    Handling Requests And Responses in Node.js
    Node.js is a powerful JavaScript runtime for building server-side applications. It provides an efficient way to handle HTTP requests and responses using the built-in http module or frameworks like Express.js.Understanding HTTP Requests and ResponsesAn HTTP request is sent by a client (browser or API
    4 min read
    File handling in Node.js
    The most important functionalities provided by programming languages are Reading and Writing files from computers. Node.js provides the functionality to read and write files from the computer. Reading and Writing the file in Node.js is done by using one of the coolest Node.js modules called fs modul
    4 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences