When I was learning more about NodeJS and how exactly it works, I was faced with the following question: How does NodeJS exactly use the V8 engine?
I don't know if you know, but JavaScript is not a language that is compiled to machine level (transforming to bytes) itself. You need to use a compiler to make this magic for you. And that's exactly what engine V8 does. It took (somehow) the JS code and compiled it to your computer run and understand. Now, how it is done?
Firstly, the runtime needs to interpret what is written in your language and convert it to machine-level language. After, they took this code and compiled it. This process could take a while in some runtimes, and everything has to be optimized as much as possible to be efficient.
To overcome this problem, V8 doesn’t interpret everything first and then compile to binary. Otherwise, V8 has a Just-in-Time approach. That means it interpreter and compiler line by line at the same time. This saves time and makes the compiler faster.
Ok, but how NodeJS is involved?
NodeJS use the V8 engine in the heart of the application to compile all the JS code. But this is not the only use.
Going deeply, Node uses some of the V8 functionalities such as Garbage Collector (GB), PromisseHooks, heaps and space statistics, serialization and deserialization. Of course, all those functionalities have some Node implementation on top of that to become easy to apply. But if you want, you can access these functionalities. For instance, you can access the four lifecycles of a PromisseHooks (init, resolve, before, and after stages). As one of the Node contributors (Erick Wendel) said,
A lot of NodeJS is nothing more than an extension customized and amplified of V8 functionalities.
So, NodeJS needs a JavaScript runtime to interpret and compile its JS code. And back in time, the V8 engine was selected to do this job. Of course, some NodeJS functions were built on top of V8 functions and it’s incredible to see how they use these functions.
Next steps
If you want to go deeply into your studies, I’d like to recommend some next steps to your studies. First of all, I strongly suggest the article series published by Lucas Santos called: Node.js Under The Hood. He brilliantly explained a lot of what was mentioned here and more (for example he talks about how NodeJS does GB).
Talking about GB, if you want to deeply understand this topic, I strongly recommend this article by Peter Marshall one of the contributors to the V8 engine.
And if you want some hands-on experience to thrive in, please check this tutorial by Erick Wendel creating NodeJS from scratch.
Top comments (0)