/usr/share/doc/nodejs/api
NameSizeModeActions
assets/-0755rm
addons.html851720644editdlrm
addons.json.gz111880644editdlrm
addons.md410130644editdlrm
all.html45980480644editdlrm
all.json.gz6816430644editdlrm
assert.html1106650644editdlrm
assert.json.gz120070644editdlrm
assert.md471470644editdlrm
async_hooks.html835990644editdlrm
async_hooks.json.gz140850644editdlrm
async_hooks.md388880644editdlrm
buffer.html2457620644editdlrm
buffer.json.gz241050644editdlrm
buffer.md1050440644editdlrm
child_process.html1367670644editdlrm
child_process.json.gz193990644editdlrm
child_process.md629190644editdlrm
cli.html879360644editdlrm
cli.json.gz166150644editdlrm
cli.md422630644editdlrm
cluster.html601160644editdlrm
cluster.json.gz95570644editdlrm
cluster.md254260644editdlrm
console.html460930644editdlrm
console.json.gz60560644editdlrm
console.md164310644editdlrm
crypto.html2830430644editdlrm
crypto.json.gz321180644editdlrm
crypto.md1251980644editdlrm
debugger.html180890644editdlrm
debugger.json.gz28200644editdlrm
debugger.md61330644editdlrm
deprecations.html1385370644editdlrm
deprecations.json.gz184700644editdlrm
deprecations.md791200644editdlrm
dgram.html624250644editdlrm
dgram.json.gz96300644editdlrm
dgram.md277460644editdlrm
dns.html982890644editdlrm
dns.json.gz138380644editdlrm
dns.md407990644editdlrm
documentation.html109780644editdlrm
documentation.json33280644editdlrm
documentation.md22470644editdlrm
domain.html363010644editdlrm
domain.json.gz63550644editdlrm
domain.md155210644editdlrm
embedding.html181650644editdlrm
embedding.json.gz36250644editdlrm
embedding.md88110644editdlrm
errors.html1829820644editdlrm
errors.json.gz364790644editdlrm
errors.md817340644editdlrm
esm.html924900644editdlrm
esm.json.gz150540644editdlrm
esm.md484660644editdlrm
events.html759860644editdlrm
events.json.gz95610644editdlrm
events.md288230644editdlrm
fs.html4371790644editdlrm
fs.json.gz470950644editdlrm
fs.md1877350644editdlrm
globals.html197950644editdlrm
globals.json.gz25250644editdlrm
globals.md58380644editdlrm
http.html1643780644editdlrm
http.json.gz258880644editdlrm
http.md744650644editdlrm
http2.html2564510644editdlrm
http2.json.gz371570644editdlrm
http2.md1217220644editdlrm
https.html383450644editdlrm
https.json.gz48470644editdlrm
https.md139420644editdlrm
index.html100870644editdlrm
index.json540644editdlrm
index.md18250644editdlrm
inspector.html224330644editdlrm
inspector.json.gz33380644editdlrm
inspector.md68250644editdlrm
intl.html231540644editdlrm
intl.json.gz40380644editdlrm
intl.md110920644editdlrm
module.html217390644editdlrm
module.json.gz28210644editdlrm
module.md53410644editdlrm
modules.html613330644editdlrm
modules.json.gz118970644editdlrm
modules.md306100644editdlrm
n-api.html3403820644editdlrm
n-api.json.gz486820644editdlrm
n-api.md2062680644editdlrm
net.html951130644editdlrm
net.json.gz142650644editdlrm
net.md404730644editdlrm
os.html586580644editdlrm
os.json.gz85760644editdlrm
os.md346320644editdlrm
packages.html654830644editdlrm
packages.json.gz124010644editdlrm
packages.md365380644editdlrm
path.html393210644editdlrm
path.json.gz48730644editdlrm
path.md147500644editdlrm
perf_hooks.html562150644editdlrm
perf_hooks.json.gz69730644editdlrm
perf_hooks.md201160644editdlrm
policy.html159080644editdlrm
policy.json.gz29080644editdlrm
policy.md63240644editdlrm
process.html1693410644editdlrm
process.json.gz277340644editdlrm
process.md821620644editdlrm
punycode.html169040644editdlrm
punycode.json.gz19390644editdlrm
punycode.md40630644editdlrm
querystring.html193340644editdlrm
querystring.json.gz25190644editdlrm
querystring.md54230644editdlrm
readline.html584340644editdlrm
readline.json.gz88350644editdlrm
readline.md251330644editdlrm
repl.html541520644editdlrm
repl.json.gz100530644editdlrm
repl.md237540644editdlrm
report.html449410644editdlrm
report.json.gz62270644editdlrm
report.md182870644editdlrm
stream.html2005010644editdlrm
stream.json.gz344850644editdlrm
stream.md986190644editdlrm
string_decoder.html144150644editdlrm
string_decoder.json.gz15450644editdlrm
string_decoder.md29340644editdlrm
synopsis.html114750644editdlrm
synopsis.json30130644editdlrm
synopsis.md21290644editdlrm
timers.html274670644editdlrm
timers.json.gz36370644editdlrm
timers.md97380644editdlrm
tls.html1483810644editdlrm
tls.json.gz299880644editdlrm
tls.md813880644editdlrm
tracing.html195860644editdlrm
tracing.json.gz28290644editdlrm
tracing.md67560644editdlrm
tty.html269300644editdlrm
tty.json.gz37580644editdlrm
tty.md89890644editdlrm
url.html974950644editdlrm
url.json.gz136110644editdlrm
url.md448690644editdlrm
util.html1780810644editdlrm
util.json.gz205420644editdlrm
util.md712550644editdlrm
v8.html446880644editdlrm
v8.json.gz60820644editdlrm
v8.md155330644editdlrm
vm.html1033920644editdlrm
vm.json.gz140230644editdlrm
vm.md482930644editdlrm
wasi.html170880644editdlrm
wasi.json.gz28140644editdlrm
wasi.md59320644editdlrm
worker_threads.html708080644editdlrm
worker_threads.json.gz113260644editdlrm
worker_threads.md338830644editdlrm
zlib.html901240644editdlrm
zlib.json.gz105690644editdlrm
zlib.md356970644editdlrm
Edit: /usr/share/doc/nodejs/api/embedding.md (8811B)
# C++ Embedder API Node.js provides a number of C++ APIs that can be used to execute JavaScript in a Node.js environment from other C++ software. The documentation for these APIs can be found in [src/node.h][] in the Node.js source tree. In addition to the APIs exposed by Node.js, some required concepts are provided by the V8 embedder API. Because using Node.js as an embedded library is different from writing code that is executed by Node.js, breaking changes do not follow typical Node.js [deprecation policy][] and may occur on each semver-major release without prior warning. ## Example embedding application The following sections will provide an overview over how to use these APIs to create an application from scratch that will perform the equivalent of `node -e `, i.e. that will take a piece of JavaScript and run it in a Node.js-specific environment. The full code can be found [in the Node.js source tree][embedtest.cc]. ### Setting up per-process state Node.js requires some per-process state management in order to run: * Arguments parsing for Node.js [CLI options][], * V8 per-process requirements, such as a `v8::Platform` instance. The following example shows how these can be set up. Some class names are from the `node` and `v8` C++ namespaces, respectively. ```cpp int main(int argc, char** argv) { argv = uv_setup_args(argc, argv); std::vector args(argv, argv + argc); std::vector exec_args; std::vector errors; // Parse Node.js CLI options, and print any errors that have occurred while // trying to parse them. int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str()); if (exit_code != 0) { return exit_code; } // Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way // to create a v8::Platform instance that Node.js can use when creating // Worker threads. When no `MultiIsolatePlatform` instance is present, // Worker threads are disabled. std::unique_ptr platform = MultiIsolatePlatform::Create(4); V8::InitializePlatform(platform.get()); V8::Initialize(); // See below for the contents of this function. int ret = RunNodeInstance(platform.get(), args, exec_args); V8::Dispose(); V8::ShutdownPlatform(); return ret; } ``` ### Per-instance state Node.js has a concept of a “Node.js instance”, that is commonly being referred to as `node::Environment`. Each `node::Environment` is associated with: * Exactly one `v8::Isolate`, i.e. one JS Engine instance, * Exactly one `uv_loop_t`, i.e. one event loop, and * A number of `v8::Context`s, but exactly one main `v8::Context`. * One `node::IsolateData` instance that contains information that could be shared by multiple `node::Environment`s that use the same `v8::Isolate`. Currently, no testing if performed for this scenario. In order to set up a `v8::Isolate`, an `v8::ArrayBuffer::Allocator` needs to be provided. One possible choice is the default Node.js allocator, which can be created through `node::ArrayBufferAllocator::Create()`. Using the Node.js allocator allows minor performance optimizations when addons use the Node.js C++ `Buffer` API, and is required in order to track `ArrayBuffer` memory in [`process.memoryUsage()`][]. Additionally, each `v8::Isolate` that is used for a Node.js instance needs to be registered and unregistered with the `MultiIsolatePlatform` instance, if one is being used, in order for the platform to know which event loop to use for tasks scheduled by the `v8::Isolate`. The `node::NewIsolate()` helper function creates a `v8::Isolate`, sets it up with some Node.js-specific hooks (e.g. the Node.js error handler), and registers it with the platform automatically. ```cpp int RunNodeInstance(MultiIsolatePlatform* platform, const std::vector& args, const std::vector& exec_args) { int exit_code = 0; // Set up a libuv event loop. uv_loop_t loop; int ret = uv_loop_init(&loop); if (ret != 0) { fprintf(stderr, "%s: Failed to initialize loop: %s\n", args[0].c_str(), uv_err_name(ret)); return 1; } std::shared_ptr allocator = ArrayBufferAllocator::Create(); Isolate* isolate = NewIsolate(allocator, &loop, platform); if (isolate == nullptr) { fprintf(stderr, "%s: Failed to initialize V8 Isolate\n", args[0].c_str()); return 1; } { Locker locker(isolate); Isolate::Scope isolate_scope(isolate); // Create a node::IsolateData instance that will later be released using // node::FreeIsolateData(). std::unique_ptr isolate_data( node::CreateIsolateData(isolate, &loop, platform, allocator.get()), node::FreeIsolateData); // Set up a new v8::Context. HandleScope handle_scope(isolate); Local context = node::NewContext(isolate); if (context.IsEmpty()) { fprintf(stderr, "%s: Failed to initialize V8 Context\n", args[0].c_str()); return 1; } // The v8::Context needs to be entered when node::CreateEnvironment() and // node::LoadEnvironment() are being called. Context::Scope context_scope(context); // Create a node::Environment instance that will later be released using // node::FreeEnvironment(). std::unique_ptr env( node::CreateEnvironment(isolate_data.get(), context, args, exec_args), node::FreeEnvironment); // Set up the Node.js instance for execution, and run code inside of it. // There is also a variant that takes a callback and provides it with // the `require` and `process` objects, so that it can manually compile // and run scripts as needed. // The `require` function inside this script does *not* access the file // system, and can only load built-in Node.js modules. // `module.createRequire()` is being used to create one that is able to // load files from the disk, and uses the standard CommonJS file loader // instead of the internal-only `require` function. MaybeLocal loadenv_ret = node::LoadEnvironment( env.get(), "const publicRequire =" " require('module').createRequire(process.cwd() + '/');" "globalThis.require = publicRequire;" "require('vm').runInThisContext(process.argv[1]);"); if (loadenv_ret.IsEmpty()) // There has been a JS exception. return 1; { // SealHandleScope protects against handle leaks from callbacks. SealHandleScope seal(isolate); bool more; do { uv_run(&loop, UV_RUN_DEFAULT); // V8 tasks on background threads may end up scheduling new tasks in the // foreground, which in turn can keep the event loop going. For example, // WebAssembly.compile() may do so. platform->DrainTasks(isolate); // If there are new tasks, continue. more = uv_loop_alive(&loop); if (more) continue; // node::EmitBeforeExit() is used to emit the 'beforeExit' event on // the `process` object. node::EmitBeforeExit(env.get()); // 'beforeExit' can also schedule new work that keeps the event loop // running. more = uv_loop_alive(&loop); } while (more == true); } // node::EmitExit() returns the current exit code. exit_code = node::EmitExit(env.get()); // node::Stop() can be used to explicitly stop the event loop and keep // further JavaScript from running. It can be called from any thread, // and will act like worker.terminate() if called from another thread. node::Stop(env.get()); } // Unregister the Isolate with the platform and add a listener that is called // when the Platform is done cleaning up any state it had associated with // the Isolate. bool platform_finished = false; platform->AddIsolateFinishedCallback(isolate, [](void* data) { *static_cast(data) = true; }, &platform_finished); platform->UnregisterIsolate(isolate); isolate->Dispose(); // Wait until the platform has cleaned up all relevant resources. while (!platform_finished) uv_run(&loop, UV_RUN_ONCE); int err = uv_loop_close(&loop); assert(err == 0); return exit_code; } ``` [`process.memoryUsage()`]: process.html#process_process_memoryusage [CLI options]: cli.html [deprecation policy]: deprecations.html [embedtest.cc]: https://github.com/nodejs/node/blob/master/test/embedding/embedtest.cc [src/node.h]: https://github.com/nodejs/node/blob/master/src/node.h