Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,9 @@ coverage-report-js:
# Runs the C++ tests using the built `cctest` executable.
cctest: all
@out/$(BUILDTYPE)/$@ --gtest_filter=$(GTEST_FILTER)
$(NODE) ./test/embedding/test-embedding.js
@out/$(BUILDTYPE)/embedtest "require('./test/embedding/test-embedding.js')"
@out/$(BUILDTYPE)/napi_embedding "require('./test/embedding/test-napi-embedding.js')"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Could we please change napi_* to node_api_* for all newly introduced elements across the entire PR?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gabrielschulhof this is the name of the unit test, most unit tests / benchmarks that test Node-API use the napi abbreviation

@out/$(BUILDTYPE)/napi_modules ../../test/embedding/cjs.cjs ../../test/embedding/es6.mjs

.PHONY: list-gtests
list-gtests:
Expand Down Expand Up @@ -565,7 +567,9 @@ test-ci: | clear-stalled bench-addons-build build-addons build-js-native-api-tes
$(PYTHON) tools/test.py $(PARALLEL_ARGS) -p tap --logfile test.tap \
--mode=$(BUILDTYPE_LOWER) --flaky-tests=$(FLAKY_TESTS) \
$(TEST_CI_ARGS) $(CI_JS_SUITES) $(CI_NATIVE_SUITES) $(CI_DOC)
$(NODE) ./test/embedding/test-embedding.js
out/Release/embedtest 'require("./test/embedding/test-embedding.js")'
out/Release/napi_embedding 'require("./test/embedding/test-napi-embedding.js")'
out/Release/napi_modules ../../test/embedding/cjs.cjs ../../test/embedding/es6.mjs
$(info Clean up any leftover processes, error if found.)
ps awwx | grep Release/node | grep -v grep | cat
@PS_OUT=`ps awwx | grep Release/node | grep -v grep | awk '{print $$1}'`; \
Expand Down
39 changes: 39 additions & 0 deletions doc/api/embedding.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,47 @@ int RunNodeInstance(MultiIsolatePlatform* platform,
}
```

## Node-API Embedding

<!--introduced_in=REPLACEME-->

As an alternative, an embedded Node.js can also be fully controlled through
Node-API. This API supports both C and C++ through [node-addon-api][].

An example can be found [in the Node.js source tree][napi_embedding.c].

```c
napi_platform platform;
napi_env env;
const char *main_script = "console.log('hello world')";

if (napi_create_platform(0, NULL, NULL, &platform) != napi_ok) {
fprintf(stderr, "Failed creating the platform\n");
return -1;
}

if (napi_create_environment(platform, NULL, main_script,
(napi_stdio){NULL, NULL, NULL}, NAPI_VERSION, &env) != napi_ok) {
fprintf(stderr, "Failed running JS\n");
return -1;
}

// Here you can interact with the environment through Node-API env

if (napi_destroy_environment(env, NULL) != napi_ok) {
return -1;
}

if (napi_destroy_platform(platform) != napi_ok) {
fprintf(stderr, "Failed destroying the platform\n");
return -1;
}
```

[CLI options]: cli.md
[`process.memoryUsage()`]: process.md#processmemoryusage
[deprecation policy]: deprecations.md
[embedtest.cc]: https://github.com/nodejs/node/blob/HEAD/test/embedding/embedtest.cc
[napi_embedding.c]: https://github.com/nodejs/node/blob/HEAD/test/embedding/napi_embedding.c
[node-addon-api]: https://github.com/nodejs/node-addon-api
[src/node.h]: https://github.com/nodejs/node/blob/HEAD/src/node.h
139 changes: 139 additions & 0 deletions doc/api/n-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -6581,6 +6581,145 @@ idempotent.

This API may only be called from the main thread.

## Using embedded Node.js

### `napi_create_platform`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

```c
napi_status napi_create_platform(int argc,
char** argv,
napi_error_message_handler err_handler,
napi_platform* result);
```

* `[in] argc`: CLI argument count, pass 0 for autofilling.
* `[in] argv`: CLI arguments, pass NULL for autofilling.
* `[in] err_handler`: If different than NULL, will be called back with each
error message. There can be multiple error messages but the API guarantees
that no calls will be made after the `napi_create_platform` has returned.
In practice, the implementation of graceful recovery is still in progress,
and many errors will be fatal, resulting in an `abort()`.
* `[out] result`: A `napi_platform` result.

This function must be called once to initialize V8 and Node.js when using as a
shared library.

### `napi_destroy_platform`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

```c
napi_status napi_destroy_platform(napi_platform platform);
```

* `[in] platform`: platform handle.

Destroy the Node.js / V8 processes.

### `napi_create_environment`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

```c
napi_status napi_create_environment(napi_platform platform,
napi_error_message_handler err_handler,
const char* main_script,
int32_t api_version,
napi_env* result);
```

* `[in] platform`: platform handle.
* `[in] err_handler`: If different than NULL, will be called back with each
error message. There can be multiple error messages but the API guarantees
that no calls will be made after the `napi_create_platform` has returned.
In practice, the implementation of graceful recovery is still in progress,
and many errors will be fatal, resulting in an `abort()`.
* `[in] main_script`: If different than NULL, custom JavaScript to run in
addition to the default bootstrap that creates an empty
ready-to-use CJS/ES6 environment with `global.require()` and
`global.import()` functions that resolve modules from the directory of
the compiled binary.
It can be used to redirect `process.stdin`/ `process.stdout` streams
since Node.js might switch these file descriptors to non-blocking mode.
* `[in] api_version`: Node-API version to conform to, pass `NAPI_VERSION`
for the latest available.
* `[out] result`: A `napi_env` result.

Initialize a new environment. A single platform can hold multiple Node.js
environments that will run in a separate V8 isolate each. If the returned
value is `napi_ok` or `napi_pending_exception`, the environment must be
destroyed with `napi_destroy_environment` to free all allocated memory.

### `napi_run_environment`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

```c
napi_status napi_run_environment(napi_env env);
```

* `[in] env`: environment handle.

Iterate the event loop of the environment. Executes all pending
JavaScript callbacks. Cannot be called with JavaScript on the
stack (ie in a JavaScript callback).

### `napi_await_promise`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

```c
napi_status napi_await_promise(napi_env env,
napi_value promise,
napi_value *result);
```

* `[in] env`: environment handle.
* `[in] promise`: JS Promise.
* `[out] result`: Will receive the value that the Promise resolved with.

Iterate the event loop of the environment until the `promise` has been
resolved. Returns `napi_pending_exception` on rejection. Cannot be called
with JavaScript on the stack (ie in a JavaScript callback).

### `napi_destroy_environment`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

```c
napi_status napi_destroy_environment(napi_env env);
```

* `[in] env`: environment handle.

Destroy the Node.js environment / V8 isolate.

## Miscellaneous utilities

### `node_api_get_module_file_name`
Expand Down
20 changes: 20 additions & 0 deletions lib/internal/bootstrap/switches/is_embedded_env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

// This is the bootstrapping code used when creating a new environment
// through Node-API

// Set up globalThis.require and globalThis.import so that they can
// be easily accessed from C/C++

/* global primordials */

const { globalThis } = primordials;
const cjsLoader = require('internal/modules/cjs/loader');
const esmLoader = require('internal/process/esm_loader').esmLoader;

globalThis.module = new cjsLoader.Module();
globalThis.require = require('module').createRequire(process.execPath);

const parent_path = require('url').pathToFileURL(process.execPath);
globalThis.import = (mod) => esmLoader.import(mod, parent_path, { __proto__: null });
globalThis.import.meta = { url: parent_path };
105 changes: 105 additions & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
'src/module_wrap.cc',
'src/node.cc',
'src/node_api.cc',
'src/node_api_embedding.cc',
'src/node_binding.cc',
'src/node_blob.cc',
'src/node_buffer.cc',
Expand Down Expand Up @@ -1188,6 +1189,110 @@
],
}, # embedtest

{
'target_name': 'napi_embedding',
'type': 'executable',

'dependencies': [
'<(node_lib_target_name)',
'deps/histogram/histogram.gyp:histogram',
'deps/uvwasi/uvwasi.gyp:uvwasi',
],

'includes': [
'node.gypi'
],

'include_dirs': [
'src',
'tools/msvs/genfiles',
'deps/v8/include',
'deps/cares/include',
'deps/uv/include',
'deps/uvwasi/include',
'test/embedding',
],

'sources': [
'src/node_snapshot_stub.cc',
'test/embedding/napi_embedding.c',
],

'conditions': [
['OS=="solaris"', {
'ldflags': [ '-I<(SHARED_INTERMEDIATE_DIR)' ]
}],
# Skip cctest while building shared lib node for Windows
[ 'OS=="win" and node_shared=="true"', {
'type': 'none',
}],
[ 'node_shared=="true"', {
'xcode_settings': {
'OTHER_LDFLAGS': [ '-Wl,-rpath,@loader_path', ],
},
}],
['OS=="win"', {
'libraries': [
'Dbghelp.lib',
'winmm.lib',
'Ws2_32.lib',
],
}],
],
}, # napi_embedding

{
'target_name': 'napi_modules',
'type': 'executable',

'dependencies': [
'<(node_lib_target_name)',
'deps/histogram/histogram.gyp:histogram',
'deps/uvwasi/uvwasi.gyp:uvwasi',
],

'includes': [
'node.gypi'
],

'include_dirs': [
'src',
'tools/msvs/genfiles',
'deps/v8/include',
'deps/cares/include',
'deps/uv/include',
'deps/uvwasi/include',
'test/embedding',
],

'sources': [
'src/node_snapshot_stub.cc',
'test/embedding/napi_modules.c',
],

'conditions': [
['OS=="solaris"', {
'ldflags': [ '-I<(SHARED_INTERMEDIATE_DIR)' ]
}],
# Skip cctest while building shared lib node for Windows
[ 'OS=="win" and node_shared=="true"', {
'type': 'none',
}],
[ 'node_shared=="true"', {
'xcode_settings': {
'OTHER_LDFLAGS': [ '-Wl,-rpath,@loader_path', ],
},
}],
['OS=="win"', {
'libraries': [
'Dbghelp.lib',
'winmm.lib',
'Ws2_32.lib',
],
}],
],
}, # napi_modules

{
'target_name': 'overlapped-checker',
'type': 'executable',
Expand Down
Loading