Blocking & Non Blocking in NodeJs

Blocking & Non Blocking in NodeJs

NodeJs Part 4

·

2 min read

  • 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

Did you find this article valuable?

Support Dhanush N by becoming a sponsor. Any amount is appreciated!