2

我刚刚开始使用 Node.js,并且我在 Python 和 C++ 方面有相当多的背景知识。我知道 Node.js 是一个运行时环境,但我很难理解它对代码的实际作用,使其不同于编译器。如果有人能解释运行时环境与典型编译器和解释器的具体区别,那就更好了。

4

3 回答 3

2

Let's take it this way:

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine.

V8 is the Google Javascript engine, the same engine is used by Google Chrome. There are other JS engines like SpiderMonkey used by Firefox, JavaScriptCore used by Safari, and Edge was originally based on Chakra but it has been rebuilt to use the V8 engine.

We must understand the relationship first before moving to how the V8 works.

JavaScript engine is independent of the browser in which it's hosted. This key feature enabled the rise of Node.js. V8 was chosen to be the engine that powered Node.js.

Since V8 is independent and open-source, we can embed it into our C++ programs, and Nodejs itself is just a program written in C++. Nodejs took the V8 and enhanced it by adding features that a server needs.

JavaScript is generally considered an interpreted language, but modern JavaScript engines no longer just interpret JavaScript, they compile it.

Since you have a C++ background, C++ performs what is called ahead-of-time (AOT) compilation, the code is transformed during compilation into machine code before the execution.

JavaScript on the other side is internally compiled by V8 with just-in-time (JIT) compilation is done during execution. While the code is being executed by the interpreter it will keep track of functions that are called very often and mark them as hot functions then it will compile them to machine code and store them.

于 2021-10-24T14:18:59.453 回答
1

编译器是将代码从一种语言转换为另一种语言的程序。例如,在 Java 中,我们有一个 java 编译器javac,您可以在.java文件上运行它来将您的代码编译成与平台无关的 java 文件(任何 jvm 都可以理解和执行)。由于您是 JavaScript 新手,您会遇到转译器(如 babel),它们会转变您的下一代JavaScript 代码转换为所有浏览器(甚至是旧浏览器)都可以处理的遗留 JavaScript 代码。运行时是一个更模糊的概念。它可以从在特定操作系统上运行编译代码的一组函数变为程序运行的整个环境。对于 NodeJS,它是您可以在浏览器之外运行 JavaScript 程序的环境。它采用了在 Chrome 浏览器上运行 JavaScript 的 V8 引擎,并使其随处可用。这就是 JavaScript 如何从仅在浏览器上运行的客户端编程语言转变为可以在配备运行时环境 NodeJS 的服务器上运行的服务器端编程语言。

于 2021-10-24T07:45:50.930 回答
-1

一些简单的点可能会有所帮助:

  1. C/C++ 代码将由 C/C++ 编译器编译成机器代码,不需要任何运行时环境即可运行(大多数情况下,运行时库除外)

  2. Python 代码需要 Python 解释器来执行它。正如你所说,你有 C++/Python 的背景,你必须熟悉所有这些细节

  3. JavaScript 本来是要在浏览器中运行的,而且大多数情况下都是这样,但是一些聪明的人想到在浏览器之外运行它,他们创建了 JavaScript 执行引擎(它是一种独立的 JavaScript 执行器),而 Node.js 只是其中之一. 它只是在自己的浏览器之外运行 JavaScript 代码。执行仍然是对 JavaScript 代码的解释,因此它只是一个解释器,具有大量的支持功能,用于管理运行时依赖项、包管理等。

于 2021-10-24T07:58:27.927 回答