Skip to main content

Command Palette

Search for a command to run...

Blocking & Non Blocking in NodeJs

NodeJs Part 4

Updated
2 min read
Blocking & Non Blocking in NodeJs
D

Experienced Consultant, Full Stack Developer, R&D Engineer who loves to solve puzzles & technology problems by code/

  • In Node.js, JavaScript code runs in a single thread. When a piece of code is executed, it blocks the execution of any other code until it finishes.

  • The above means that if a long-running task, such as a database query or a file read, is executed, the rest of the code in the thread will be blocked until the task completes.

  • Blocking code in Node.js can make the application unresponsive and slow.

  • To mitigate this, Node.js provides non-blocking APIs for performing I/O operations. These APIs, such as the fs module for file system operations, allow you to pass in a callback function that will be executed when the operation is complete.

  • This way, the rest of the code in the thread can continue to execute while the I/O operation is performed in the background.

Blocking Code Example:

In this, the program will wait for the file to be read completely before executing the next line of code

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

Non-Blocking Code Example:

In this case, the program will execute the next line of code and will not wait for the file to be completely read; it will execute the callback after reading the file.

fs.readFile('file.txt', (err, data) => {
    console.log(data);
});
console.log('Doing other things...');

Thanks for reading ❤️ Hope you learned something

Any other inputs or recommendations feel free to share below

Follow me via Twitter, Github, Instagram

Node.js Concepts

Part 5 of 8

In this series I will be writing about node js concepts in form of minimal blogs which would help you in understanding the various concepts of node.js

Up next

Timers in NodeJs

NodeJs Part 6

More from this blog

Dhanush N

56 posts

Experienced Consultant & Software Engineer with experience around building and scaling applications over various emerging technologies. I love solving puzzles & provide technological solutions by code