preface

This article will show you how the V8 engine executes JavaScript code.

After reading this article, you can master the following aspects:

  • JavaScript implementation principle;
  • The actual structure of the browser kernel;
  • The working process of browser rendering engine;
  • How the V8 engine works;
  • Differences and exercises between the browser and Node.js architectures;
  • Application scenarios of node. js architecture and REPL;
  • Node.js schema REPL usage;

PS: This article is the first in a “Node.js series” about encountering Node.js. I will continue to write one or two node.js articles a week, and I welcome you to join me in learning the big Front-end Advanced series.


The V8 engine mentioned in the title is naturally associated with Node.js.

Let’s take a look at the official definition of Node.js:

Node.js is a JavaScript runtime environment based on the V8 JavaScript engine

But this sentence for many of our students, very general, such as first throw out such a few questions:

  • What is a JavaScript runtime environment?
  • Why does JavaScript need a special runtime environment?
  • What is a JavaScript engine?
  • What is V8?

The above questions, students understand the general no matter, this article will reveal the answer in turn ~

Let’s get those concepts straight before we look at what Node is. Why the big front end needs it.

JavaScript is everywhere

Jeff Atwood, one of the founders of Stack Overflow, proposed the famous Atwood law a few years ago:

  • Anything you can useJavaScript to implementeventuallyUsing JavaScript.

At its inception, JavaScript was designed to be used for simple scripting tasks in the browser, performing various operations on the browser and the DOM within it, so its application scenarios are very limited.

But with the advent of Node, Atwood’s Law has been proven more and more to be true.

But to understand how Node.js helps us do this, we have to understand how JavaScript is run.

Now let’s think about how JavaScript code is executed in the browser.

Browser kernel

Different browsers have different kernel components:

  • Gecko: Early used by Netscape and Mozilla Firefox browsers;
  • Trident: Developed by Microsoft and used by Internet Explorer 4 to Internet Explorer 11, but Edge has moved to Blink.
  • Webkit: Open source, kHTml-based, developed by Apple for Safari and previously used by Google Chrome;
  • Blink: a branch of Webkit, developed by Google and currently used in Google Chrome, Edge, Opera, etc.
  • And so on…

In fact, we often refer to the browser kernel as the browser’s typography engine:

Layout engine, also known as browser Engine, rendering engine, or boilerplate engine.

After introducing the browser’s typesetting engine, let’s introduce the working process of browser’s rendering engine.

How the rendering engine works

As shown above:

  • HTML and CSS are parsed by the corresponding Parser to form the corresponding DOM Tree and CSS Tree.
  • They will form a Render Tree after additional synthesis, while generating a Layout Layout, and finally through the browser’s rendering engine to help us complete the rendering, showing the Hmtl page we usually see;
  • During HTML parsing, if you encounter a<script src='xxx'>, stops parsing HTML in favor of loading and executing JavaScript code (which is done by the JavaScript engine)

Because JavaScript is a high-level language (Python, C++, Java), the JavaScript engine converts it into assembly language, which is then converted into machine language (binary 010101), which is then executed by the CPU.

JavaScript engine

Why do you need a JavaScript engine?

  • In fact, the JavaScript that we write, whether you send it to the browser or Node, is executed by the CPU;
  • But the CPU only knows that its own instruction set, which is actually machine language, can be executed by the CPU;
  • So we need the JavaScript engine to help us translate JavaScript code into CPU instructions for execution;

What are some common JavaScript engines?

  • SpiderMonkey: The first JavaScript engine, developed by Brendan Eich (JavaScript writer);
  • Chakra: Developed by Microsoft for IT browsers;
  • JavaScriptCore: JavaScript engine in WebKit, developed by Apple;
  • V8: Google developed a powerful JavaScript engine that also helped Chrome stand out from other browsers;

So we’ve introduced the JavaScript engine and the browser kernel, but some of you might be asking what’s the connection between the two and what’s the difference?

Next, I’ll use the WebKit kernel as an example.

Its kernel

In fact, the WebKit kernel consists of two parts:

  • WebCore: responsible for HTML parsing, layout, rendering, etc.
  • JavaScriptCore: Parse and execute JavaScript code (the work of the JavaScript engine);

Another powerful JavaScript engine is the V8 engine.

V8 engine

Let’s take a look at the official definition of V8:

  • Supported languages: V8 is Google’s open source high-performance JavaScript and WebAssembly engine written in C ++ for Chrome and Node.js, among others;

    V8 can run JavaScript, assembly language compiled by the WebAssembly engine, etc.

  • Cross-platform: It implements ECMAScript and WebAssembly and runs on Windows 7 or later, macOS 10.12+ and uses X64, IA-32,

    Running on Linux with AN ARM or MIPS processor;

  • Embedded: V8 can run independently or be embedded into any C ++ application;

How a V8 engine works

Illustration of how a V8 engine works

Among them **Parse(parser), Lgnition (interpreter), and TurboFan(compiler optimizer)** are all built-in modules of the V8 engine

Suppose you have a snippet of JavaScript source code like this:

console.log("hello world");

function sum(num1, num2) {
	return num1 + num2;
}
Copy the code
  • The Parse module converts JavaScript code into an AST (abstract syntax tree) because the interpreter does not know JavaScript code directly.

    • If the function is not called, it will not be converted to an AST.
    • Parse’s official V8 documentation: v8.dev/blog/scanne…
  • Ignition is an interpreter that converts an AST into a ByteCode;

    • At the same time, TurboFan will collect the information required for optimization (such as the type information of function parameters, which can be used for real calculation);
    • If the function is called only once, Ignition will do the interpreted execution ByteCode;
    • Ignition V8: V8. dev/blog/igniti…
  • TurboFan is a compiler that compiles bytecode to machine code that the CPU can execute directly;

    • If a function is called multiple times, it is marked as a hotspot function and is converted by TurboFan into optimized machine code to improve performance.
    • However, machine code is actually restored to ByteCode, because if the type changes during the subsequent execution of the function (for example, sum used to perform number, but later changed to String), the optimized machine code does not handle the operation correctly and is converted to ByteCode in reverse.
    • TurboFan V8: V8.dev /blog/ Turbof…
  • That’s how the JavaScript code is executed, and the fact that V8’s memory reclaim is another reason why it’s powerful;

    • Orinoco module, which is responsible for garbage collection, reclaiming unwanted memory in the program;
    • Orinoco’s V8 official document: v8.dev/blog/trash-…
    • aboutV8 engine garbage memory collection mechanismYou can read this article I put together before”Classic sublimation” V8’s garbage memory collection mechanism

Programming languages fall into two broad categories:

  • Interpreted languages: relatively inefficient (such as JavaScript)
  • Compiled languages: relatively efficient (e.g. C++)

The above situation corresponds to the general execution flow of JavaScript interpreted language, but compiled language is often not, such as C++, for example, some applications in the system are written in C++, when executing, they are directly converted into machine language (binary format 010101), and handed to the CPU for uniform execution. Such operation efficiency is natural relatively high some.

However, V8 also makes an optimization for interpreted programming languages. The TurboFan optimization compiler, as mentioned above, allows TurboFan to capture a JavaScript function that is called multiple times into optimized machine code and then hand it over to the CPU to improve the performance of the code.

Review: What is Node.js

Review: Official definition of Node.js:

Node.js is a JavaScript runtime environment based on the V8 JavaScript engine.

Node.js executes JavaScript code based on the V8 engine, but it’s not just V8:

  • We learned earlier that V8 can be embedded in any C ++ application, whether it’s Chrome or Node.js, and it’s actually embedded in V8

    To execute JavaScript code;

  • However, the Chrome browser also needs to parse and render HTML, CSS and other related rendering engines, and also needs to provide support for browser operations

    API, the browser’s own event loop, etc., all done for us by the browser kernel;

  • In addition, there are some additional operations that need to be performed in Node.js, such as file system read/write, network IO, encryption, compression and decompression of files, etc

    Operation;

PS: In the next article, I’ll take you step by step into the world of Node.js…

Browser and Node.js architecture differences

A quick comparison of node.js and browser architectures:

  • In Chrome

    • The V8 engine is just a small part of this, which is designed to help JavaScript code run;

    • There are also browser kernels that take care of HTML parsing, layout, rendering, and so on.

    • Middle tier and operating system (NIC/hard disk/graphics card…) ;

      • For example, to send a network request, the middle tier calls the network card in the operating system;
      • Reading some local files, the middle tier calls the hard disk in the operating system;
      • To render the browser page, the middle tier calls the graphics card in the operating system;
      • And so on…
  • In the Node

    • V8 engines;
    • The middle layer (LiBUV) includes EventLoop, etc.
    • Operating system (NIC/hard disk/graphics card…) ;

Node. Js framework

Let’s look at a separate node.js architecture diagram:

  • The JavaScript code we write will pass through the V8 engine and then through the Node.js Bindings (Node.js API) to distribute the task to the Libuv event loop.
  • Libuv provides event loops, file system reads and writes, network IO, thread pools, and more; Libuv is a library written in C;

For the specific internal code execution process, I will explain the event queue mechanism and the principle of asynchronous IO in node.js in the following articles.

Application scenarios of Node.js

The rapid development of Node.js also makes enterprises pay more and more attention to Node.js technology.

So what are the practical application scenarios?

  • Currently, front-end development libraries are managed as node packages;
  • NPM and YARN tools are the most commonly used tools for front-end development.
  • More and more companies are using Node.js as web server development;
  • A large number of projects need to use Node.js to complete the isomorphic application of front and back rendering;
  • Many enterprises are using Electron to develop desktop applications;

Node. Js REPL

What is a REPL? It feels so high

  • REPL is short for read-eval-print Loop, which translates as “read-evaluation-output” Loop.
  • The REPL is a simple, interactive programming environment;

In fact, the console of our browser can be viewed as a REPL.

Node also gives us a REPL environment where we can walk through simple code.

Thank you all 💙

If you found this post inspiring, I’d like to invite you to do three small favors for me:

  1. Point a “look”, let more people can also see this content (like not to see, are playing rogue -_-)
  2. Follow the public number “front time house”, continue to push good posts for you
  3. If you feel good about it, you can also read time House Howe’s recent articles (thanks to digg’s encouragement and support 🌹🌹🌹).
    • “Soul work” 2020 score 30 high-frequency JS hand-torn interview questions (811+👍)
    • This article takes you to master JS advanced programming skills! Fierce! (100 + 👍)
    • Several cross-domain solutions commonly used in front-end development (50+👍)