Overview of Node.js

Tram Ho

1. Introduction

The name Node.js must be no stranger to web developers. Node.js was created by Ryan Dahl in 2009 based on the Google V8 JavaScript engine. As we all know Node.js is a single thread that uses a single-thread event loop to handle multiple request simultaneously.

With popular server-side languages ​​like PHP, .NET, JAVA … using multi-threads mechanism, we can easily imagine how it works. For each request to the server will create a separate thread to handle. But Node.js has only one thread to handle all request . To understand why Node.js has only one thread but can handle many request simultaneously, let’s take a look at some of the following basic concepts.

2. Call Stack

The first thing we learn will be the call stack . In simple terms, the call stack is where the function is being executed. call stack works under the FILO mechanism, below is a small example:

  • bar() is called and pushed into the call stack
  • foo() is called and pushed into the call stack
  • Print out foo
  • foo() is removed from the call stack
  • Print out bar
  • bar() is removed from the call stack

3. Event Loop & Event Queue

Another example

The result returned will be

Although the time is set to 0, but 2 still printed after 3 . The reason is that setTimeout is an async action so foo() was not immediately executed and pushed into the event queue .

event loop is a continuous loop that checks to see if the call stack empty and will pick up an event from the event queue and push it onto the call stack . Because the call stack must be empty for the event from the event queue to be pushed, the result will be:

  • bar() is called and pushed into the call stack
  • Print out 1
  • setTimeout is executed, the bar is pushed into the event queue
  • Print out 3
  • bar() is removed from the call stack
  • foo() is pushed into the call stack
  • Print out 2
  • foo() is removed from the call stack

4. Conclusion

Each request to the Node server is considered an event and is pushed into the event queue . With the examples and explanations above, you probably already understand why Node.js has only 1 thread but can handle multiple request simultaneously.

Although in the introduction I wrote Node.js has only 1 thread but not really like that. Node.js has other threads running in parallel to handle asynchronous tasks. In the event loop example, if you replace setTimeout with another function to retrieve data from the DB , the connection to the DB to retrieve data will be performed on another thread and will push the callback into the event queue after it is finished.

Share the news now

Source : Viblo