In this article, we willlook intoNode.jsand V8. Node.jsis a very important part oftheJavaScriptecosystem, as it is used in the backend to produce a complete application. It is often considered a part of the popularMERN(MongoDB,ExpressJS,ReactJSandNode.js) stack and MEAN (MongoDB,ExpressJS,AngularandNode.js) stack.
TheV8 engine is what powersNode.jsand it is anopen-source engine on which even Chrome works.It parses and runsyour JavaScript inside aNode environment.
Overview on Node.js
Node.jswas created by Ryan Dahl in 2009 and since then it has becomeavery popular backend technology. Till then the backend was dominated by languages like PHP,ASP.NETand Java. It has become popular becauseit enablesa Frontend developer with JavaScript skillstoeasily create full stack apps.
The formal definition ontheofficial Node.jswebsitedescribes Node.jsas “a JavaScript runtime built on Chrome’s V8 JavaScript engine.”
Node.jscame into existence when its creatorRyan Dahl, understandingthe power of V8, powered theChrome browser and extended it so that it can run on your machine as a standalone application.
Another part of the definition ontheofficial Node.js website says,Node.js uses an event driven, non-blocking I/O model that makes it lightweight and efficient.
I/O refers to input/output and this is where the additional functionality of Node.jscomes into play. We can read and edit local files in Node.jsand alsodoanHTTP request to an API.
The earlier backend systems like PHP and ASP used to block the program till a network requestwas complete. But it was completely changed by Node.JS, which sends the request and then goesto the next line of code. So, it is non-blocking and faster than the earlier backend technologies.
But it is a single-threaded technology and that is where it has somelimitations,whereasJava shines because ofit beingmulti-threaded.
Yet another part of the official definition ontheNode.js website says,Node.js package ecosystem,npmis the largest ecosystem ofopen-sourcelibraries in the world.
Over the pastdecade, an amazing community ofopen-sourceenthusiasts have created more than 1 millionnpmpackages, which enhancethe capabilities ofNode.js.
It is completely open-sourceand anyone can use it,as ithasanMIT licence,for developing server-side and networking applications. It can run on all three Operating Systemsi.e.,Mac OS,Windows,and Linux.
Overview on V8JavaScriptengine
V8 isGoogle’sopen-source JavaScript engine, which is written in C++. It was developed in 2008 for Google Chrome and Chromium based browsers (like Brave), butwas used to build Node.jsfor server-side coding. In fact, the V8 engine, is also used by JSON basedNo-SQLdatabases like Couchbase and the popularMongoDB.Besidesthis,V8 also powers the popular desktop application framework Electron and the latest server-side runtime environment of Deno.
V8 isaJavaScript engine, because it takes our JavaScript and executes it while browsing in Chrome. Itactually providesa runtime environment in which JavaScript executes. The great thing about this isthattheJavaScript engine is independent of the browser in which it executes. Thisis thefeaturethatprompted the creator of Node.JS to choose V8 engine to power Node.JS and the rest is history.The popularity ofNode.JS exploded andtheV8 enginewas also used to create desktop frameworks and databases.
There are other JavaScript engines likeSpiderMonkeyused by Firefox,andJavaScript Coreused by Safari. Microsoft’s Edge was originally based on Chakra JavaScript engine, buthas beenrecently re-builtwith Chromium and V8 engine.
How V8 Engine works
A JavaScript Engine is an interpreterwhichexecutes JavaScript code. We can create JavaScript engine in two ways –thefirstwayisto implement as a standard interpreter which is done bySpiderMonkeyfrom Mozilla. The other way is the Just-in-time (JIT) compilation, which converts the native JavaScript code to machine code and that is the way V8 usesit. So, the difference between V8 code and others is that it does not produce any intermediate code.
When a developer or program runs a JavaScript onV8(i.e.in browser orNode environment), theIgnitioninterpreter compiles the JavaScript code and generates non-optimized machine code. On runtime, the machine code isanalyzedand re-compiledfor best performance, by theTurbofanandCrankshaftcomponents of V8.
The V8 engine also uses some other components,along with the ones we had seen above. They areLiftoffandOrinoco–
- Liftoff is responsible for machine code generation in a highly optimized way. It generates code for each opcode and perform way better then Turbofan.
- Orinoco is responsible for garbage collection. It looks for disconnected memory allocations and perform operations to free up more space. It also update the pointers to new memory locations.
V8 also uses a lot of different threads and they are –
- The primary thread fetches and compiles the JavaScript code.
- There is another thread which is used to optimize the running code, while the primary thread continues its execution.
- Yet another thread is used for profiling, which tellson runtime the methodsthat areneeded to be optimized.
- Some of the threads also do garbage collection.
The Just-in-Time Paradigm
We will learn a bit more about the Just-in-Time (JIT) compilation in V8. For a code to execute in any programming language, itmustbe converted into machine code, which the computer understands. Thereisadifferent paradigm for this transformation.
Most of the traditional languages created before JavaScript like C++ and Java, perform something called Ahead-of-Time compilation. Here, the code is transformed intomachine code before the execution of our program during compile time. Anyone who hasworked with Java or C++ knows that we run commands like below to compile a Java or C++ program.
javac MyJavaProgram.javag++ -omycppprogrammycppprogram.cpp
This converts the code into machine code after whichwe can run our program with commands like below.
java MyJavaProgram./mycppprogram
On the other hand, in languages like JavaScript andPython, each line of code is executed at runtime. This is done because it is impossible to know the exact code before execution. In a browser,you never compile a code first and then run it, because it is done automatically behind thescenes.
So, the Ahead-of-Time compilation produces more optimized and fast code, because of the compilation done before hand.Which is why interpretation done by languages like JavaScript are slower.
To overcome this problem in dynamic languages, the approach of Just-in-Time (JIT) compilation, was created, which combines the best of both interpretation and compilation. So, an interpretation step runs before the compilation step, where the V8 engine detectsthe more frequently used functions andcodeandcompilesthem using information from previous executions.
Duringcompiletime,this code is re-compiled for optimal performance.
What is the relationship between Node and V8?
The Node.jsisreferredto as aruntime environment, which includes everything you need to run a program written in JavaScript.
The core powering Node.js is this V8 engine. The diagram shows a comparison with the Java Virtual Machine (JVM), which power the Java Runtime environment. Beside the V8 engine the Node.js runtime environment adds many Node APIs to power the Node.js environment. We can also extend the functionality of our node code by installing additional npm packages.
One thing to understand is that V8 is essentially an independent C++ library, that is used by Node or Chromium to run JavaScript code. V8 exposes an API that other code can use, so if you have your own C++ program, you can embed V8 in it and runaJavaScript program. That ishow it is doneby Node and Chrome.
Suppose,we want to add a functionality in our JavaScript code to have statements likeprint(‘hello world’), in addition to theconsole.log(‘Hello World’). We can add our own implementation of print function in C++, in V8, which is anyway open sourced.
Can Node.jswork without V8?
The current Node.js engine cannot work without V8. It would have no JavaScript engine and hence no ability to run any JavaScript code.The fact is that the native code bindings, which come withNode.js like the fs module and theNet module, rely on the V8 interface between C++ and JavaScript.
Although in the tech world everything is possible and Microsoft in July 2016,made an effortto use Chakra JavaScript engine (which was used inEdge browser at that time) inNode.jsand replace the V8 engine,that project never took off and MicrosoftEdge itself recently moved to Chromium, which uses V8 JavaScript engine.
Thenew kid on the block forserver-side programming isDENO. Many considerthat it could bea replacementtoNode.jsin the next 2-3 years,and italso uses V8 JavaScript engine under its hood.
Looking to land a job in the tech industry? Look no further! Discover the best Python course that guarantees job opportunities. Start your journey today and unlock endless career possibilities. Don't miss out!
Summary
We havegotan overview of Node.jsruntime environment and V8 JavaScript engine in this post. Then, we have gone through the working oftheV8 engine. We alsoinvestigateddetails ofthe Just-in-Time compilation, used by V8 JavaScript engine. Also, we haveunderstoodthe relationship between Node.js and V8 engine and how V8 engine is independent of Node.js.
Lastly, we have learnt that it is not possible for Node.js to run without a JavaScript engine like V8.It can, however,be replaced by another JavaScript engine like Chakra from Microsoft; even thoughthis is highlyimprobable,itisstill possible.