What is Node.js?
We can draw analogy
between JavaScript runtime & Java Virtual Machine. A ‘virtual machine’ refers
to the software-driven emulation of a given computer system. There are many
types of virtual machines, and they are classified by how precisely they are
able to emulate or substitute for actual physical machines.
A ‘system virtual machine’, for example, provides a complete
emulation of a platform on which an operating system can be executed.e.g.
Virtual Box & Parallels
A ‘process virtual machine’, on the other hand, is less
fully-functional and can run one program or process. Wine is a process virtual machine that allows you to run
Windows applications on a Linux machine, but does not provide an entire Windows
OS on a Linux box.
There are other JavaScript runtime than V8 too. Notably few
are Microsoft’s Chakra & Spider Monkey. But Node.js which an open source
project stick to V8.
Node.js uses an event-driven, non-blocking
I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest
ecosystem of open source libraries in the world.
An event can be defined as "a significant change in state.
What is callback function?
A reference to executable code, or a piece of executable
code, that is passed as an argument to other code.
Let’s explore real
life example. You go to Pizza Store order quite few pizzas & Cokes, now the
pizza can’t be made at speed of thought so the counter guy will ask you about
your contact number. No need for you to wait at counter & you can happily
do something else. Once pizza got ready pizza counter guy will ring you that’s kind
of callback.
function PizzaMaker(orderandContactDetails, callback) {
console.log("time consuming
task of making pizza based on order, blocked execution till It finish");
//ring
the guy ,hey your pizza is ready
callback();
}
Calling PizzaMaker the function with callback as follows
var _orderandContactDetails
= {"type":"onion
paneer","contact":"34535456436","extraCheese":"yes","takeAwayOrder":"yes"};
PizzaMaker(orderandContactDetails ,function(error,result){
if(error){
console.log("take a refund
& go to other restaurant");
}
else{
console.log("take a home
yummy pizza");
}
});
Here PizzaMaker is host function & below
anonymous function is callback function which we are passing to host function.
function(error,result){
if(error){
console.log(“take a refund & go to other restaurant”);
}else{
console.log(“take a home yummy pizza”);
}
}
Convention:
Often last parameter of host function is used
for callback function while callback
function’s first parameter is used for passing error & second parameter
used to pass result. It entirely depends upon host function implementation. It
is not binding to keep callback function bi parametered or maintain order of
parameter.
W.r.t. our example, Event
of finished making pizza order is trigger to callback. Callback is one of the
most basic approaches in event driven model. Many native functions in node.js
core library do implement callback. Though there is other approach like promise
too.
Asynchronous Nature
of Node.js:
Consider below example
const fs = require('fs');
console.log('Before loop');
fs.readFile('./sample.txt', (err, data) => {
if (err) throw err;
else {
console.log("File
Content");
console.log(data.toString());
}
});
console.log('After loop');
Output:
C:\Users\Sangram\projects\tut_async>node index.js
Before loop
After loop
File Content
ONE
TWO
THREE
Here sequence of execution is not followed in traditional
programming model text after loop would have been last.
C:\Users\Sangram\projects\tut_async>node index.js
Before loop
File Content
ONE
TWO
THREE
After loop
Here we are reading sample.txt file which is basically an IO
operation.IO operation can take long time to finish based on task it executing.
If next lines in sequence wait till completion of IO operation then it becoming
blocking but here IO operation do not block execution of next line. Similarly HTTP
Requests, Database requests are also implemented in non-blocking way in node.js.Non-blocking
nature gives node.js edge over other and make it more efficient.
Node.js provide minimal feature out of box for implementing
additional features one need to install concern package. Due to this approach
node.js has lesser memory footprint. Which makes node.js lightweight?
For
Loop & While loop
An execution of for loop & while loop is synchronous that
means until execution of loop block finishes no line below will be executed.
See below example
console.log('Before loop');
console.log("For loop");
for(var i=0;i < 5;i++){
console.log(i);
}
console.log("While loop");
var j=0
while(j < 5){
console.log(j);
j++;
}
console.log('After loop');
Output
C:\Users\Sangram\projects\tut_async>node index.js
Before loop
For loop
0
1
2
3
4
While loop
0
1
2
3
4
After loop
Here loop block executed in sequential order.
Word
of caution while mixing Blocking and Non-Blocking Code:
Consider below code.
const fs = require('fs');
fs.readFile('./sample.txt', (err, data) => {
if (err) throw err;
else{
console.log("File
Content");
console.log(data.toString());
}
});
fs.unlinkSync('./sample.txt');
Here readFile function is executing in non-blocking mode so,
before reading sample.txt finishes the unlinkSync function get called which is
deleting the very file we are trying to read.
You can correct simply by calling unlinkSync inside callback
of readFile function.
const fs = require('fs');
fs.readFile('./sample.txt', (err, data) => {
if (err) throw err;
else{
console.log("File
Content");
console.log(data.toString());
fs.unlinkSync('./sample.txt');
}
});
References
No comments:
Post a Comment