Skip to main content

Command Palette

Search for a command to run...

Blocking vs Non-Blocking Code in Node.js

Updated
4 min read

What Are We Gonna Study?

Hey there folks, hope you are doing great in your life, and enjoying every bit of it.

Today we'll talk about some topics which usually cause some silly mistakes in your code in the backend.

  1. What blocking code means

  2. What non-blocking code means

  3. Why blocking slows servers

  4. Async operations in Node.js

These topics are very necessary especailly in backend and if you are here, i think you already have strong JS fundamentals...

Now, gather all your focus right here and bear with me till the very end of it...


What Blocking Code Means?

Blocking code is basically a code which stops your JavaScript Engine from moving ahead, it keeps your engine stuck at a particular point, until and unless the operation doesn't completes.

Blocking code is always and always Synchronous code, it can never be Asynchronous.

A few examples of blocking code are:

// Reading File Synchronously through fs module

import fs from 'node:fs'

fs.readFileSync('./love-letter.md', 'utf-8')

console.log('File Reading Successful')


// Iterations
let sum = 0;
for (let i = 0; i < 1000000000; i++) {
    sum += i;
}

console.log("Calculation finished");

What Non-Blocking Code Means?

Non-Blocking code have the super power to perform the operation in the background so that your JavaScript Engine doesn't blocks.

Here are some of the examples of Non-Blocing code

import fs from 'node:fs'


// Reading file
async function readFile() {
  await fs.promises.readFile("/love-letter.md", "utf-8");
  console.log('Reading Complete')
}
// I used an async function but you can promises too!

async function hashPass() {
  await bcrypt.hash("password", 10);
  console.log("Password hashed Successfully!");
}

Why Blocking Code Slows Down Your Servers?

  • Blocking code can and will slow your server down!

  • The reason is simple, suppose that 40 users came at demanding a thing, and that operation takes almost 2 seconds to complete.

  • So, technically the blocking code will do it one-by-one for every person.

  • Which means the last person has to wait for almost 80 seconds right?

  • And what if the server somehow crashed in between, the rest of the users' time would be wasted right?

  • So, that is why Blocking code slows your servers down.

Note: Even though you might think we should always use Non-Blocking code but the truth is everything has it's own unique use case (except you in her life), you'll get to know about them when you'll build projects.


Async Operations in NodeJS

In NodeJS there are several operations we usually do that should be Async.

import User from 'db.js'

await User.create(...)
  • Don't go in syntax or keywords just try to understand what i am saying.

  • Database Calls should be async because keep in mind that database is always on another continent, so it needs time.

import fs from 'node:fs'

fs.readFile(...)
  • We use async in reading files because we'll never want that our code stops just for a file reading right?

  • But spoilers alret there are some scenarios where you use fs synchronously (blocking code) but it depends on use case, you'll probably find that out in a project.

There can be multiple examples, like:

  • Sending data to redis (don't mind for now)

  • Hashing password using bcrypt.

  • And a dozens of more.

The main thing is that you should know when to do what, and that you'll learn by building projects!


Wrap Up!

So that was it from my side folks, hope you enjoyed this blog, if yes then share it on social media, if no, then give me your feedbacks.

Anyways, I'll catch you up in the next blog until then keep coding and enjoying your life 💝

NodeJS Backend

Part 2 of 15

This is an ongoing series that will most likely cover the following topics - Async Code in Node.js: Callbacks and Promises - Sessions vs JWT vs Cookies: Understanding Authentication Approaches - Storing Uploaded Files and Serving Them in Express - URL Parameters vs Query Strings in Express.js - How Node.js Handles Multiple Requests with a Single Thread - Setting Up Your First Node.js Application Step-by-Step - Creating Routes and Handling Requests with Express - JWT Authentication in Node.js Explained Simply - What is Node.js? JavaScript on the Server Explained - Handling File Uploads in Express with Multer - What is Middleware in Express and How It Works - Why Node.js is Perfect for Building Fast Web Applications - REST API Design Made Simple with Express.js - Blocking vs Non-Blocking Code in Node.js - The Node.js Event Loop Explained

Up next

What is Node.js? JavaScript on the Server Explained

What are We Gonna Study? Hey there folks! Hope you are doing great and enjoying your dev life. Today we'll be talking about NodeJS, didn't you ever wondered why and how a language meant to be run on a

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!