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:
1 2 3 4 5 6 7 8 9 10 11 | function foo() { console.log('foo'); } function bar() { foo(); console.log('bar'); } bar(); |
bar()
is called and pushed into thecall stack
foo()
is called and pushed into thecall stack
- Print out
foo
foo()
is removed from thecall stack
- Print out
bar
bar()
is removed from thecall stack
3. Event Loop & Event Queue
Another example
1 2 3 4 5 6 7 8 9 10 11 12 | function foo() { console.log(2) } function bar() { console.log(1); setTimeout(foo, 0); console.log(3); } bar(); |
The result returned will be
1 2 3 4 | 1 3 2 |
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 thecall stack
- Print out
1
setTimeout
is executed, thebar
is pushed into theevent queue
- Print out
3
bar()
is removed from thecall stack
foo()
is pushed into thecall stack
- Print out
2
foo()
is removed from thecall 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.