Labels

Saturday, December 2, 2017

Node.JS & EventLoop Explained..

Overview:
  • Node.js is a Server-Side platform developed by Ryan Dahl in 2009 for easily building fast, scalable network applications. 
  • Node.js is a JavaScript Runtime or platform which is built on Google Chrome’s JavaScript v8 engine. This runtime allows executing the JavaScript code on any machine outside a browser (this means that it is the server that executes the Javascript and not the browser).
  • Node.js = Runtime Environment + JavaScript Library
  • Nodde.js built on Chrome’s JavaScript Engine (V8)  and designed with a Non-blocking, Event-driven I/O. 
    • Note: Its Non-blocking I/O is due to its use of asynchronous functionality, which keeps the server away from waiting on data to be returned before being able to move on to other tasks.
    • Note: Below are JavaScript Engines for different browsers that run the JavaScript of web pages.
      • Chrome : V8.
      • Firefox : Spidermonkey
      • IE: Chakra
      • Safari : JavaScriptCore 
  • Node.js is also cross-platform, able to be run on Windows, Linux and OS X. 
  • Node.js uses an Event-Driven, Non-Blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
  • Node.JS packaging eco-system is the largest eco-system of open libraries in the world.
  • Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications built on Google Chrome's JavaScript Engine (V8 Engine).

Why Node.JS (Reasons to use NodeJS)
  • Speed: Node.js is a JavaScript Runtime that uses the V8 Engine developed by Google for use in Chrome. V8 compiles and executes JavaScript at lightning speeds mainly due to the fact that V8 compiles & translates JavaScript code into more efficient machine code instead of  bytecode or any intermediate code.
  • Larget Eco-System: npm is the Node.js package manager having collection of more than 3.5 lacs of packages and it is excellent.
    • Note : Node Package Manager (NPM) makes it easy to install packages that others have developed to perform any number of tasks. This helps to encourage code-sharing among developers and to reduce the amount of custom development that has to be done when one or more packages can take care of that coding for you.
  • One Language: It runs Javascript, so you can use the same language on server and client, and even share some code between them (e.g. for form validation, or to render views at either end.)
  • Single Threaded & Event Driven : The single-threaded event-driven system is fast even when handling lots of requests at once, and also simple, compared to traditional multi-threaded Java or ROR frameworks.
  • Real-time, Made Easy with Websockets: Node.js is a great platform for creating real-time apps. With a module such as Sockiet.io, you can create real-time chats, games and more. Socket.io is one of the most popular websocket libraries in use, and makes collaborative web applications dead simple.
    • Note:  Websockets are simply two-way communications channels between the client and server. So the server can push data to the client just as easily as the client can. 
UseCases:
  • APIs based Applications
  • I/O bound Applications
  • Streaming Data
  • A Real-time Applications like online games, collaboration tools and chat rooms etc.
  • Single Page Applications
  • JSON based Applications
  • PROXY Applications


Node.JS Drawbacks:
  • Callback Hell: In Node.JS everything is asynchronous by default. This means you are likely to end up using tons of nested callbacks, which can cause multiple issues (like Debugging, Error Handling, Error Stacks etc.). Nevertheless, there are a number of solutions to this problem, e.g. async/await. Well this problem is specific to JavaScript, not Node.JS.
  • Event Loop: While the event loop is one of its' largest advantages, not understanding how this works is one of its' biggest disadvantages as well.  Do *NOT* do long running, synchronous, cpu bound logic in Node.js.  Instead spin it off to a worker queue, another thread/process (use a pool), or any number of other ways to remove the heavy lifting from your main event loop.
Few Testimonials:
  • Paypal: Node.js and an all Javascript development stack helped PayPal bring efficiencies in engineering and helped rethink and reboot product, design and operational thinking.
  • Uber: Uber used Node.js from the beginning, and its distributed system was a perfect fit, since a lot of network requests are made. The non-blocking asynchronous I/O used by Node.js helped to ensure those requests could be made and handled quickly to provide the best service possible.
jQuery vs Angular vs Node.Js:
  • jQuery (Client Side): Is a Library: Is a fast, small, lightweight, "write less, do more", and feature-rich JavaScript library - HTML document traversal and manipulation, event handling, animation et
  • Angular: (Client Side) : Is a client-side JavaScript MVC framework to develop a dynamic single-page web application. Angular was originally started as a project in Google, but now it is an open source framework.
  • Node.JS (Server-Side): Is an open source, cross-platform runtime environment for developing server-side and networking applications built on Google Chrome's JavaScript Engine (V8 Engine).

Node JS Event Loop:




















Node.JS - CallStack, CallBack & Event-Loop:

Consider below code-snippet and see Node.js Event-Driven, Non-Blocking Model works:

console.log('Starting App')
setTimeout(() => {
  console.log('First Callback 2000ms');
}, 2000);
setTimeout(() => {
  console.log('Second Callback 0ms');
}, 0);
console.log('Finisihng App')

Step1:

  1. First thing happens here is: main() statement is loaded in CallStack and kick-offs the execution.
  2. Next the very first statement is loaded in CallStack and removed after execution.
  3. Next statement loads in CallStack. But as this is a Node API and not available in V8 engine, moves/registers to Node API section and finally gets removed from CallStack. Here in Node APIs section API starts it's execution in parallel to CallStack.
  4. Next statement (with zero sec) adds in CallStack. But as this is a Node API and not available in V8 engine, moves/registers to Node API section and finally gets removed from CallStack. Here in Node APIs section API starts it's execution in parallel to CallStack.
  5. After this assume, API with zero sec is completed. Thus it moves to CallBack queue, marking itself ready for execution. Ideally CallBack queue is the place where the operation resides and wait for execution immediately after CallStack complete it's all operations and becomes empty. This is all taken care by 'Event Loop', where it does not push any operation waiting in CallBack queue, unless CallBack becomes empty.
  6. Thus next statement comes to execute is 'Finishing App' in CallStack. Once it's completed main() statement moves out of CallStack.
  7. Now here 'Event Loop' finds empty CallStack, it moves first waiting operation in CallBack Queue to CallStack. This CallBack executes Console.Log ('Second CallBack') and then removes from CallStack.
  8. We still have one more operation running in Node API, which moves to CallBack queue after completion. Event Loop then moves this operation in Call Stack as in Step 7.
  9. Once all the operations are complete and every section - CallStack, Node API and CallBack Queue is empty, whole operation is marked complete.
Step 1


Step 2

Step 3 (a)

Step 3 (b)

Step 3(c)

Step 4(a)

Step 4(b)

Step 4(c)

Step 5

Step 6(a)

Step 6(b)

Step 6(c)

Step 7(a)

Step 7(b)

Step 7(c)
Step 8(a)

Step 8(b)

Step 8(c)



Hope this helps!!

Arun Manglick

No comments:

Post a Comment