# 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][].
V8 supports [fast API calls][], which can be useful for improving the
performance in certain cases.
## libuv API documentation
The other major dependency of Node.js is [libuv][], providing
the [event loop][] and other operating 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
程序员Chino的日记
- 粉丝: 3715
- 资源: 5万+
最新资源
- 基于bilibili弹幕分析,包含爬虫、词云分析、词频分析、情感分析、构建衍生指标,可视化资料齐全+详细文档+源码.zip
- 基于Python 网络爬虫实战、数据分析合集 当当 网易云音乐 unsplash 必胜客 猫眼资料齐全+详细文档+源码.zip
- 基于python flask vue-element-admin selenium 爬虫 后台资料齐全+详细文档+源码.zip
- 基于Python爬虫小项目汇总(招聘信息电影信息股票信息天气信息贴吧信息图片信息视频信息..)资料齐全+详细文档+源码.zip
- 基于python模拟登陆一些大型网站资料齐全+详细文档+源码.zip
- 基于scrapy + selenium + phantomjs + mongodb机票爬虫(去哪儿和携程网)资料齐全+详细文档+源码.zip
- 基于rocket电商网站爬虫合集,淘宝京东亚马逊等资料齐全+详细文档+源码.zip
- 基于Python入门网络爬虫之精华版资料齐全+详细文档+源码.zip
- 基于Scrapy + seleniumwebdriver + 爬取某书整站爬虫资料齐全+详细文档+源码.zip
- 基于scrapy+scrapy-redis+selenium+pandas+matplotlibaqi天气信息爬虫、清洗资料齐全+详细文档+源码.zip
- 基于selenium + sqlite3 爬虫,实现将淘宝网站数据、1688网站数据的爬取,淘宝爬虫1688爬虫;并保存到数据库中资料齐全+详细文档+源码.zip
- 基于scrapy分布式爬虫,selenium 爬虫,手机群控(自动化)反爬破解文档资料齐全+详细文档+源码.zip
- 基于selenium 携程酒店爬虫+简单数据分析资料齐全+详细文档+源码.zip
- 基于selenium+python实现京东商品爬虫淘宝店铺爬虫资料齐全+详细文档+源码.zip
- 基于selenium裁判文书网爬虫,文书网登录资料齐全+详细文档+源码.zip
- 基于Selenium×Firefox自动化爬虫模板资料齐全+详细文档+源码.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈