Lines Matching +full:node +full:- +full:api
1 # Node.js C++ codebase
3 Hi! You’ve found the C++ code backing Node.js. This README aims to help you
9 Node.js has a document detailing its [C++ coding style][]
12 ## V8 API documentation
14 A lot of the Node.js codebase is around what the underlying JavaScript engine,
15 V8, provides through its API for embedders. Knowledge of this API can also be
16 useful when working with native addons for Node.js written in C++, although for
17 new projects [N-API][] is typically the better alternative.
19 V8 does not provide much public API documentation beyond what is
23 * On GitHub: [`v8.h` in Node.js master][]
29 embedder API.
34 ## libuv API documentation
36 The other major dependency of Node.js is [libuv][], providing
37 the [event loop][] and other operation system abstractions to Node.js.
39 There is a [reference documentation for the libuv API][].
43 A number of concepts are involved in putting together Node.js on top of V8 and
53 The `v8::Isolate` is often passed to other V8 API functions, and provides some
57 V8 APIs are not thread-safe unless explicitly specified. In a typical Node.js
63 happen on a per-`Isolate` basis.
65 Typical ways of accessing the current `Isolate` in the Node.js code are:
69 * Given a [`Context`][], using `context->GetIsolate()`.
70 * Given a [`Environment`][], using `env->isolate()`.
80 <a id="internal-fields"></a>
83 V8 provides the ability to store data in so-called “internal fields” inside
84 `v8::Object`s that were created as instances of C++-backed classes. The number
88 In most native Node.js objects, the first internal field is used to store a
94 * `obj->InternalFieldCount()` to look up the number of internal fields for an
96 * `obj->GetInternalField(i)` to get a JavaScript value from an internal field.
97 * `obj->SetInternalField(i, v)` to store a JavaScript value in an
99 * `obj->GetAlignedPointerFromInternalField(i)` to get a `void*` pointer from an
101 * `obj->SetAlignedPointerInInternalField(i, p)` to store a `void*` pointer in an
106 <a id="js-handles"></a>
109 All JavaScript values are accessed through the V8 API through so-called handles,
112 <a id="local-handles"></a>
119 Most of the V8 API uses `Local` handles to work with JavaScript values or return
143 v8::Isolate* isolate = context->GetIsolate();
154 if (obj->Get(context, foo_string).ToLocal(&return_value)) {
173 // CHECK() is a Node.js utilitity that works similar to assert().
174 CHECK(some_value->IsUint8Array());
178 Generally, using `val.As<v8::X>()` is only valid if `val->IsX()` is true, and
190 <a id="global-handles"></a>
194 class `Persistent`, although use of that is discouraged in Node.js) is a
198 Global handles can be either strong or weak. Strong global handles are so-called
202 is garbage-collected.
222 garbage-collected while the JavaScript Engine instance is alive, even if
229 JavaScript allows multiple global objects and sets of built-in JavaScript
231 heap. Node.js exposes this ability through the [`vm` module][].
236 Currently, in Node.js there is one main `Context` associated with an
237 [`Environment`][] instance, and most Node.js features will only work inside
240 Node.js, and a sufficiently committed person could restructure Node.js to
241 provide built-in modules inside of `vm.Context`s.
244 Typical ways of accessing the current `Context` in the Node.js code are:
246 * Given an [`Isolate`][], using `isolate->GetCurrentContext()`.
247 * Given an [`Environment`][], using `env->context()` to get the `Environment`’s
250 <a id="event-loop"></a>
253 The main abstraction for an event loop inside Node.js is the `uv_loop_t` struct.
256 in the course of running a Node.js program.
258 The current event loop can be accessed using `env->event_loop()` given an
260 is not inherent to the design of Node.js, and a sufficiently committed person
261 could restructure Node.js to provide e.g. the ability to run parts of Node.js
267 Node.js instances are represented by the `Environment` class.
276 different Node.js modules, for example a libuv timer for `setTimeout()` or
283 Typical ways of accessing the current `Environment` in the Node.js code are:
287 * Given a [`BaseObject`][], using `env()` or `self->env()`.
295 <a id="isolate-data"></a>
298 Every Node.js instance ([`Environment`][]) is associated with one `IsolateData`
305 inside Node.js code, e.g. given an `Environment` instance `env` the JavaScript
306 string “name” can be accessed through `env->name_string()` without actually
315 Node.js provides a `NodePlatform` class that implements the `v8::Platform`
318 The platform can be accessed through `isolate_data->platform()` given an
321 * The current Node.js instance was not started by an embedder; or
322 * The current Node.js instance was started by an embedder whose `v8::Platform`
323 implementation also implement’s the `node::MultiIsolatePlatform` interface
324 and who passed this to Node.js.
326 <a id="binding-functions"></a>
334 CHECK(args[0]->IsArrayBufferView());
335 args.GetReturnValue().Set(args[0].As<ArrayBufferView>()->HasBuffer());
340 Node.js source code.)
342 `args[n]` is a `Local<Value>` that represents the n-th argument passed to the
345 Node.js.
349 floating-point number or a `Local<Value>` to set the return value.
351 Node.js provides various helpers for building JS classes in C++ and/or attaching
352 C++ functions to the exports of a built-in module:
361 env->SetMethod(target, "getaddrinfo", GetAddrInfo);
362 env->SetMethod(target, "getnameinfo", GetNameInfo);
366 env->SetMethodNoSideEffect(target, "canonicalizeIP", CanonicalizeIP);
372 env->NewFunctionTemplate(ChannelWrap::New);
374 channel_wrap->InstanceTemplate()->SetInternalFieldCount(1);
375 channel_wrap->Inherit(AsyncWrap::GetConstructorTemplate(env));
378 env->SetProtoMethod(channel_wrap, "queryAny", Query<QueryAnyWrap>);
379 env->SetProtoMethod(channel_wrap, "queryA", Query<QueryAWrap>);
381 env->SetProtoMethod(channel_wrap, "querySoa", Query<QuerySoaWrap>);
382 env->SetProtoMethod(channel_wrap, "getHostByAddr", Query<GetHostByAddrWrap>);
384 env->SetProtoMethodNoSideEffect(channel_wrap, "getServers", GetServers);
387 FIXED_ONE_BYTE_STRING(env->isolate(), "ChannelWrap");
388 channel_wrap->SetClassName(channel_wrap_string);
389 target->Set(env->context(), channel_wrap_string,
390 channel_wrap->GetFunction(context).ToLocalChecked()).Check();
394 // `internalBinding('cares_wrap')` in Node.js’s built-in JavaScript code:
398 <a id="exception-handling"></a>
402 as C++ exceptions are disabled inside of Node.js:
407 as return values from API functions that can run JavaScript code and therefore
424 not failed. A lot of Node.js’s source code does **not** follow this rule, and
431 * Calls to functions like `object->Get(...)` or `object->Set(...)` may fail on
435 provided from Node.js internals or V8 internals, will fail when JavaScript
438 e.g. Node.js is used as an embedded library. These exceptions can happen at
441 to unexpected getters and setters, accessing some types of built-in objects
442 like `Map`s and `Set`s can also run V8-internal JavaScript code.
451 | ---------------------- | ------------------------------- |
480 v8::Isolate* isolate = context->GetIsolate();
485 for (uint32_t i = 0; i < array_of_integers->Length(); i++) {
487 if (array_of_integers->Get(context, i).ToLocal(&entry)) {
493 if (!entry->IsNumber()) {
494 // Let’s just skip any non-numbers. It would also be reasonable to throw
503 sum += entry_as_number->Value();
513 CHECK(args[0]->IsArray());
516 if (!SumNumbers(args.GetIsolate()->GetCurrentContext(),
530 `node::errors::TryCatchScope` in Node.js. The latter has the additional feature
531 of providing the ability to shut down the program in the typical Node.js way
540 <a id="libuv-handles-and-requests"></a>
546 long-lived objects that can emit events multiple times, such as network sockets
549 In Node.js, handles are often managed through a [`HandleWrap`][] subclass.
551 Requests are one-time asynchronous function calls on the event loop, such as
554 In Node.js, requests are often managed through a [`ReqWrap`][] subclass.
558 When a Node.js [`Environment`][] is destroyed, it generally needs to clean up
561 <a id="cleanup-hooks"></a>
566 `env->AddCleanupHook(callback, hint);` and
567 `env->RemoveCleanupHook(callback, hint);`, where callback takes a `void* hint`
582 `env->CloseHandle()`, which works the same way but keeps track of the number
589 `env->IncreaseWaitingRequestCounter()` and
590 `env->DecreaseWaitingRequestCounter()` functions need to be used to keep track
600 `env->can_call_into_js()` flag and do not proceed if it is set to `false`.
606 A large number of classes in the Node.js C++ codebase refer to other objects.
610 Node.js applications.
626 Node.js, and most classes that are associated with JavaScript objects are
636 `self->object()`, given a `BaseObject` named `self`.
649 Environment* env = session->env();
650 Local<Context> context = env->context();
651 Isolate* isolate = env->isolate();
711 instance, and only changes when the object is re-used in some way.
722 (As the naming has made its way into Node.js’s public API, it’s not worth
741 Environment* env = wrap->env();
742 HandleScope handle_scope(env->isolate());
743 Context::Scope context_scope(env->context());
748 Local<Value> argv[] = { Integer::New(env->isolate(), status), arr };
749 wrap->MakeCallback(env->onchange_string(), arraysize(argv), argv);
764 current Node.js [`Environment`][] is destroyed, e.g. when a Worker thread stops.
767 overview over libuv handles managed by Node.js.
779 overview over libuv handles managed by Node.js.
781 <a id="callback-scopes"></a>
796 `InternalCallbackScope callback_scope(this);`) suffices inside of Node.js’s
801 Node.js uses a few custom C++ utilities, mostly defined in [`util.h`][].
805 Node.js provides `Malloc()`, `Realloc()` and `Calloc()` functions that work
807 (As V8 does not handle out-of-memory situations gracefully, it does not make
808 sense for Node.js to attempt to do so in all cases.)
813 #### Optional stack-based memory allocation
820 The `Utf8Value`, `TwoByteValue` (i.e. UTF-16 value) and `BufferValue`
829 CHECK(args[0]->IsString());
830 Utf8Value path(env->isolate(), args[0]);
840 Node.js provides a few macros that behave similar to `assert()`:
858 ### Scope-based cleanup
884 [C++ coding style]: ../doc/guides/cpp-style-guide.md
885 [Callback scopes]: #callback-scopes
886 [JavaScript value handles]: #js-handles
887 [N-API]: https://nodejs.org/api/n-api.html
891 [`Global`]: #global-handles
893 [`IsolateData`]: #isolate-data
895 [`Local`]: #local-handles
897 [`MessagePort`]: https://nodejs.org/api/worker_threads.html#worker_threads_class_messageport
899 [`async_hooks` module]: https://nodejs.org/api/async_hooks.html
907 [`v8.h` in Node.js master]: https://github.com/nodejs/node/blob/master/deps/v8/include/v8.h
909 [`vm` module]: https://nodejs.org/api/vm.html
910 [binding function]: #binding-functions
911 [cleanup hooks]: #cleanup-hooks
912 [event loop]: #event-loop
913 [exception handling]: #exception-handling
914 [internal field]: #internal-fields
916 [libuv handles]: #libuv-handles-and-requests
917 [libuv requests]: #libuv-handles-and-requests
919 [reference documentation for the libuv API]: http://docs.libuv.org/en/v1.x/