Apparently, the most interesting aspect of NodeJS is that it uses Non Blocking coding practices. This is one of the main reason why there is JavaScript in NodeJS, because JavaScript supports callbacks, which are the key in implementing non blocking coding tactics. To get the understanding of what non blocking code would look like, let’s understand the possible scenarios where the code could go blocking.
- Reading File
- Writing File
- Querying Database
- Making a service call
- Calling an API, etc.,
Let’s work on a problem and see how NodeJS would handle it.
The Blocking Approach
Consider the situation where we need to read the content from a file.
This would comprise of 3 simple steps as depicted above. In above case each step is depending on the result of it’s predecessor. For instance, we cannot print the content of the file unless the file is read. If suppose the operation 1 would have taken 5 sec to complete followed by 2 and 1 sec for the remaining steps, the overall process would take 5 + 2 + 1 = 8 sec to complete. And for this 8 seconds, all the other operations would be blocked.
That is to say, the server would be busy unless the operation completes and therefore would not be able to process other incoming requests.
NodeJS introduces callback to overcome the problem.
The Non Blocking Approach
This is how NodeJS look at the problem, it started reading the file and do not waits for the operation to complete. Instead it registers a callback event in it’s memory, and starts doing other stuffs. Once the file reading is complete, the NodeJS remembers the callback it registered lately for this operation, so it calls that callback and therefore print the content of the file.
This approach is rather sophisticated as there are no stuffs that’s blocking the execution cycle of the program and the server is free almost every time. Well, this is good. The more the time server is free the more the number of incoming requests it can handle.
I hope this post would have served its purpose of establishing the basic understanding of the blocking and non-blocking coding tactics. Stay tuned for more.
0 comments