# Node.js C++ codebase
Hi! ð You've found the C++ code backing Node.js. This README aims to help you
get started working on it and document some idioms you may encounter while
doing so.
## Coding style
Node.js has a document detailing its [C++ coding style][]
that can be helpful as a reference for stylistic issues.
## V8 API documentation
A lot of the Node.js codebase is around what the underlying JavaScript engine,
V8, provides through its API for embedders. Knowledge of this API can also be
useful when working with native addons for Node.js written in C++, although for
new projects [N-API][] is typically the better alternative.
V8 does not provide much public API documentation beyond what is
available in its C++ header files, most importantly `v8.h`, which can be
accessed online in the following locations:
* On GitHub: [`v8.h` in Node.js][]
* On GitHub: [`v8.h` in V8][]
* On the Chromium project's Code Search application: [`v8.h` in Code Search][]
V8 also provides an [introduction for V8 embedders][],
which can be useful for understanding some of the concepts it uses in its
embedder API.
Important concepts when using V8 are the ones of [`Isolate`][]s and
[JavaScript value handles][].
## libuv API documentation
The other major dependency of Node.js is [libuv][], providing
the [event loop][] and other operation system abstractions to Node.js.
There is a [reference documentation for the libuv API][].
## File structure
The Node.js C++ files follow this structure:
The `.h` header files contain declarations, and sometimes definitions that don't
require including other headers (e.g. getters, setters, etc.). They should only
include other `.h` header files and nothing else.
The `-inl.h` header files contain definitions of inline functions from the
corresponding `.h` header file (e.g. functions marked `inline` in the
declaration or `template` functions). They always include the corresponding
`.h` header file, and can include other `.h` and `-inl.h` header files as
needed. It is not mandatory to split out the definitions from the `.h` file
into an `-inl.h` file, but it becomes necessary when there are multiple
definitions and contents of other `-inl.h` files start being used. Therefore, it
is recommended to split a `-inl.h` file when inline functions become longer than
a few lines to keep the corresponding `.h` file readable and clean. All visible
definitions from the `-inl.h` file should be declared in the corresponding `.h`
header file.
The `.cc` files contain definitions of non-inline functions from the
corresponding `.h` header file. They always include the corresponding `.h`
header file, and can include other `.h` and `-inl.h` header files as needed.
## Helpful concepts
A number of concepts are involved in putting together Node.js on top of V8 and
libuv. This section aims to explain some of them and how they work together.
<a id="isolate"></a>
### `Isolate`
The `v8::Isolate` class represents a single JavaScript engine instance, in
particular a set of JavaScript objects that can refer to each other
(the âheapâ).
The `v8::Isolate` is often passed to other V8 API functions, and provides some
APIs for managing the behaviour of the JavaScript engine or querying about its
current state or statistics such as memory usage.
V8 APIs are not thread-safe unless explicitly specified. In a typical Node.js
application, the main thread and any `Worker` threads each have one `Isolate`,
and JavaScript objects from one `Isolate` cannot refer to objects from
another `Isolate`.
Garbage collection, as well as other operations that affect the entire heap,
happen on a per-`Isolate` basis.
Typical ways of accessing the current `Isolate` in the Node.js code are:
* Given a `FunctionCallbackInfo` for a [binding function][],
using `args.GetIsolate()`.
* Given a [`Context`][], using `context->GetIsolate()`.
* Given a [`Environment`][], using `env->isolate()`.
### V8 JavaScript values
V8 provides classes that mostly correspond to JavaScript types; for example,
`v8::Value` is a class representing any kind of JavaScript type, with
subclasses such as `v8::Number` (which in turn has subclasses like `v8::Int32`),
`v8::Boolean` or `v8::Object`. Most types are represented by subclasses
of `v8::Object`, e.g. `v8::Uint8Array` or `v8::Date`.
<a id="internal-fields"></a>
### Internal fields
V8 provides the ability to store data in so-called âinternal fieldsâ inside
`v8::Object`s that were created as instances of C++-backed classes. The number
of fields needs to be defined when creating that class.
Both JavaScript values and `void*` pointers may be stored in such fields.
In most native Node.js objects, the first internal field is used to store a
pointer to a [`BaseObject`][] subclass, which then contains all relevant
information associated with the JavaScript object.
Typical ways of working with internal fields are:
* `obj->InternalFieldCount()` to look up the number of internal fields for an
object (`0` for regular JavaScript objects).
* `obj->GetInternalField(i)` to get a JavaScript value from an internal field.
* `obj->SetInternalField(i, v)` to store a JavaScript value in an
internal field.
* `obj->GetAlignedPointerFromInternalField(i)` to get a `void*` pointer from an
internal field.
* `obj->SetAlignedPointerInInternalField(i, p)` to store a `void*` pointer in an
internal field.
[`Context`][]s provide the same feature under the name âembedder dataâ.
<a id="js-handles"></a>
### JavaScript value handles
All JavaScript values are accessed through the V8 API through so-called handles,
of which there are two types: [`Local`][]s and [`Global`][]s.
<a id="local-handles"></a>
#### `Local` handles
A `v8::Local` handle is a temporary pointer to a JavaScript object, where
âtemporaryâ usually means that is no longer needed after the current function
is done executing. `Local` handles can only be allocated on the C++ stack.
Most of the V8 API uses `Local` handles to work with JavaScript values or return
them from functions.
Whenever a `Local` handle is created, a `v8::HandleScope` or
`v8::EscapableHandleScope` object must exist on the stack. The `Local` is then
added to that scope and deleted along with it.
When inside a [binding function][], a `HandleScope` already exists outside of
it, so there is no need to explicitly create one.
`EscapableHandleScope`s can be used to allow a single `Local` handle to be
passed to the outer scope. This is useful when a function returns a `Local`.
The following JavaScript and C++ functions are mostly equivalent:
```js
function getFoo(obj) {
return obj.foo;
}
```
```cpp
v8::Local<v8::Value> GetFoo(v8::Local<v8::Context> context,
v8::Local<v8::Object> obj) {
v8::Isolate* isolate = context->GetIsolate();
v8::EscapableHandleScope handle_scope(isolate);
// The 'foo_string' handle cannot be returned from this function because
// it is not âescapedâ with `.Escape()`.
v8::Local<v8::String> foo_string =
v8::String::NewFromUtf8(isolate, "foo").ToLocalChecked();
v8::Local<v8::Value> return_value;
if (obj->Get(context, foo_string).ToLocal(&return_value)) {
return handle_scope.Escape(return_value);
} else {
// There was a JS exception! Handle it somehow.
return v8::Local<v8::Value>();
}
}
```
See [exception handling][] for more information about the usage of `.To()`,
`.ToLocalChecked()`, `v8::Maybe` and `v8::MaybeLocal` usage.
##### Casting local handles
If it is known that a `Local<Value>` refers to a more specific type, it can
be cast to that type using `.As<...>()`:
```cpp
v8::Local<v8::Value> some_value;
// CHECK() is a Node.js utilitity that works similar to assert().
CHECK(some_value->IsUint8Array());
v8::Local<v8::Uint8Array> as_uint8 = some_value.As<v8::Uint8Array>();
```
Generally, using `val.As<v8::X>()` is only valid if `val->IsX()` is true, and
failing to follow that rule may lead to crashes.
##### Detecting handl
程序员Chino的日记
- 粉丝: 3723
- 资源: 5万+
最新资源
- 智能制造典型场景参考指引(2024年版).pdf
- 中国联通5G核心网安全架构及关键技术白皮书.pdf
- 基于卡尔曼滤波的车辆纵向位移、速度估计; 卡尔曼滤波(Kalman Filter,KF); Simulink仿真模型,去噪估计效果好; 基于State Space 与Matlb Function搭建
- PMSM 五相永磁同步电机的矢量控制 matlab simu link 仿真模型 (1)该模型采用 matlab simulink 2016b 版本搭建,使用matlab 2016b及以上版本打开最佳
- 基于MPC的USV自主航行仿真研究MATLAB源码+实验报告
- 第6章 WPS办公软件.zip
- 基于MPC的USV自主航行仿真研究源码+文档报告
- labview做的曲线处理,包络线判断功能,判断准确 一个demo,有源码
- Android/java面试题大全 第一部分
- droop(非线性负载),基于T型三电平逆变器的非线性负载下同步发电机控制,中点电位平衡控制,电压电流双闭环控制,基波提取算法 1.droop,非线性负载 2.电压电流双闭环,基波提取算法 3.提供
- Android/java面试题大全 第二部分
- IMG20241228094913.jpg
- 储能双向变流器,可实现整流器与逆变器控制,可实现整流与逆变,采用母线电压PI外环与电流内环PI控制,可整流也可逆变实现并网,实现能量双向流动,采用SVPWM调制方式 1.双向 2.SVPWM 3.双
- 峰度- 偏度检验matlab源程序
- 消防主机,赋安调试编程软件
- 【跌倒检测系统】基于YOLOv8的跌倒检测系统 包含训练文件,测试文件,pyqt界面源码,路况裂纹数据集,权重文件,以及配置说明 因代码文件具有可复制性,一经出概不 跌倒检测图像数据集 包
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈