Mmm… long story short, I wanted to learn how the heck node works. Read a lot of docs saying it’s asynchronous, it’s single-threaded, it’s all based on the event loop and whatnot. Basically, the words were scary I mean every guy says something huge using top-notch vocabulary and it just scared the shit out of me and my brain was like
“Dude, just stop, it’s not your level.”
Well, after a continuous three 40 min sessions of Pomodoro (by the way it really works and I will write about that shortly) and 3 cups of black coffee, I think I finally got this.
Node is not single-threaded, yes it is but not exactly
WHAT!!! trust me that was my reaction when I first found that. Yes, Node is single-threaded, or no or yes… well, it basically handles the user code in single-thread(where the event loop magic happens). Obviously, Node has to be single-threaded coz Js is single-threaded but some parts are natively handled by libuv and OS which are multi-threaded. Confusing? we’ll just break it down in a more simple way and we will come back to this.
Node keeps the single thread for your code but everything runs in parallel
First, let’s start with a simple concept called synchronous and asynchronous program. A synchronous program is something that executes one thing at a time. Unless that one task isn’t finished you can’t move on to next. Whereas Asynchronous program lets you move on to the next line by running the present line parallelly. Okay, that’s easy but how Node.js achieves this? by using a powerful easy concept called callbacks.
So, now as we know how Node.js handles asynchronous code, let’s get to the real thing, the infamous event loop. An event loop is a thing that handles and processes the events and converts them into the callbacks. So, whenever an I/O call comes, Node sends that to the event loop where it gets into the task queue and starts executing as the Node returns back to the runtime environment and moves on to the next.
Hence, this is what makes Node.js great, having asynchronous code support and running it in a single thread (though not exactly). Well, I guess this covers it. I hope this makes sense if not, let me know – as I really want to know more.