We have to start with a short explanation of what Node is, just so we're on the same page.
One such scenario is a Web server. Web servers handle a lot of I/O tasks whether it's reading from the file system or communicating via the network card.
- There is a potential for code reuse between the back-end and the front-end
- The design of Node allows it to make very performant web servers
Let's start off by debunking some myths that might make it easier to follow along when we start to code.
Contrary to what I've seen claimed on several occasions, Node uses a thread pool so it's multithreaded. However, the part of Node that "progresses" your code, does indeed run on a single thread. When we say "don't block the event loop" we're referring to this thread since that will prevent Node from making progress on other tasks.
We'll see exactly why blocking this thread is a problem and how that's handled.
Node internally divides its real work into two categories:
Tasks that mainly wait for some external event to occur are handled by the cross platform epoll/kqueue/IOCP event queue implemented in
libuv and in our case
Tasks that are predominately CPU intensive are handled by a thread pool. The default size of this thread pool is 4 threads, but that can be configured by the Node runtime.
I/O tasks which can't be handled by the cross platform event queue are also handled here, which is the case with file reads that we use in our example.
Most C++ extensions for Node use this thread pool to perform their work, and that is one of many reasons they are used for calculation-intensive tasks.
If you do want to know more about the Node event loop, I have one short page of the
libuv documentation I can
refer you to and two talks for you that I find great (and correct) on this subject:
This first talk one is held by @piscisaureus and is an excellent 15 minute overview. I especially recommend this one as its short and to the point.
The second one is slightly longer but is also an excellent talk held by Bryan Hughes
Now, relax, get a cup of tea and sit back while we go through everything together.