Friday, May 31, 2024

NodeJS Blocking Non-blocking Code

If you are doing programming from some time, you would have definitely heard the terms blocking and non-blocking or synchronous and asynchronous. NodeJS, which uses event-driven architecture, is also capable of performing non-blocking operations even though JavaScript is single-threaded thanks to the event loop in NodeJS.

What is Blocking code

If your code is executing synchronously that means it is executing line by line if there is a function call, control waits for function execution to finish. Which means execution of any further operation is blocked until the current operation completes.

In terms of Node.js, blocking code means the execution of additional JavaScript in the Node.js process is blocked until a non-JavaScript operation completes.

For example, if you are reading a file synchronously then the actual operation of reading the file content (non-JavaScript operation) blocks any other operation until reading the file completes.

Node.js blocking code example

In the 'fs' module there is a function readFileSync() that reads the file synchronously. Using that let's see how any other operation is blocked.

In the code there is a function readFileBlocking() which takes file path as parameter and then call fs.readFileSync() with that file to read the file synchronously. Content of the file is also logged to the console.

The function readFileBlocking() is called twice to read files Hello.txt and message.txt which reside in the project root directory.

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

const readFileBlocking = (filePath) => {
    console.log('Started reading ' + filePath);
    const data = fs.readFileSync(filePath, {encoding:'utf8'});
    console.log(data);
    console.log('Finished reading ' + filePath);
}

readFileBlocking(path.join(__dirname, 'Hello.txt'));
readFileBlocking(path.join(__dirname, 'message.txt'));
console.log('Waiting for file to be read....');

On running this code output is as given below for my project structure and the content I have in the two files.

Started reading D:\NETJS\NodeJS\nodews\Hello.txt
Hello from nodeJS
Finished reading D:\NETJS\NodeJS\nodews \Hello.txt
Started reading D:\NETJS\NodeJS\nodews \message.txt
This is a message from NodeJS
Finished reading D:\NETJS\NodeJS\nodews\message.txt
Waiting for file to be read....

Thing to note here is that reading of second file starts only after finishing the read operation for the first file, until then it is blocked. The message 'Waiting for file to be read....' is also displayed at the end after finishing the I/O operations. Actually this message will make more sense with the asynchronous operation here it should be changed to

console.log('File operations completed....');

What is non-blocking code

If your code is executing asynchronously that means it may not follow the convention of executing code line by line.

With non-blocking code If there is a function call, control doesn't wait for function execution to finish. It moves on to the next operation.

There must be a mechanism so that control is notified once the operation in progress finishes and control can come back to the finished operation to do any further processing like returning any data, use data in any other logic and so on.

In terms of Node.js non-blocking code means the execution of additional JavaScript in the Node.js process is not blocked until a non-JavaScript operation completes. There is a callback function which executes for any further processing once the non-JavaScript operation completes. For example, if you are reading a file asynchronously then the actual operation of reading the file content (non-JavaScript operation) doesn't block any other operation until reading the file completes.

Node.js non-blocking code example

In the 'fs' module there is a function readFile() that reads the file asynchronously.

In the code there is a function readFileNonBlocking() which takes file path as parameter and then call fs.readFile() with that file to read the file asynchronously. Content of the file is also logged to the console.

The function readFileNonBlocking() is called twice to read files Hello.txt and message.txt which reside in the project root directory.

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

const readFileNonBlocking = (filePath) => {
    console.log('Started reading ' + filePath);
    fs.readFile(filePath, 'utf8', (err, data) => {
        if(err){
            console.error('Error while reading file', err);
            return;
        }
        console.log(data); 
        console.log('Finished reading ' + filePath);       
    });
}

readFileNonBlocking(path.join(__dirname, 'Hello.txt'));
readFileNonBlocking(path.join(__dirname, 'message.txt'));
console.log('Waiting for file to be read....');

On running this code output is as given below for my project structure and the content I have in the two files.

Started reading D:\NETJS\NodeJS\nodews\Hello.txt
Started reading D:\NETJS\NodeJS\nodews\message.txt
Waiting for file to be read....
Hello from nodeJS
Finished reading D:\NETJS\NodeJS\nodews\Hello.txt
This is a message from NodeJS
Finished reading D:\NETJS\NodeJS\nodews\message.txt

From the output you can notice that operation is not getting blocked at fs.readFile() while the file is getting read control moves on to the next operation which also happens to be another file read operation so the control moves on to the next operation while the other file is getting read. That's why message 'Waiting for file to be read....' is displayed first.

Once the file read operation completes, callback function is called which display the file content.

You can compare the output of this example to the output of the blocking example to get better clarity.

That's all for this topic NodeJS Blocking Non-blocking Code. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Introduction to Node.js
  2. Node.js REPL
  3. Creating HTTP server in Node.js
  4. How to Setup a Node.js Project
  5. NodeJS NPM Package Manager

You may also like-

  1. Reading a File in Node.js
  2. JavaScript Rest Parameter
  3. Angular Event Binding With Examples
  4. NgNonBindable Directive in Angular
  5. Array in Java With Examples
  6. Fix Scanner.nextLine() Skipping Input After Another next Methods
  7. Difference Between @Controller And @RestController Annotations in Spring
  8. Python First Program - Hello World

No comments:

Post a Comment