Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node-api: use c-based api for libnode embedding #54660

Draft
wants to merge 26 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
19e8206
node-api: use c-based api for libnode embedding
vmoroz Aug 30, 2024
a4dd991
remove node_api_delete_env_options
vmoroz Aug 30, 2024
d70e2d9
change node_api_get_strings_callback signature
vmoroz Aug 30, 2024
6bb82b8
rename functions and callbacks
vmoroz Aug 31, 2024
d174f2d
platform flags to match process init flags
vmoroz Aug 31, 2024
6e4da25
add environment flags
vmoroz Sep 1, 2024
ee97722
add environment preload callback
vmoroz Sep 3, 2024
9387c56
Update test/embedding/embedtest_concurrent_node_api.cc
vmoroz Sep 3, 2024
9a770b3
Update doc/api/embedding.md
vmoroz Sep 3, 2024
d236f28
update API based on the PR feedback
vmoroz Sep 7, 2024
593c373
add support for linked modules
vmoroz Sep 10, 2024
d0604d8
add run Node.js main and address some TODOs
vmoroz Sep 11, 2024
21efab9
add node_embedding_exit_code enum
vmoroz Sep 11, 2024
cbbe06a
simplify the Node-API code invocation
vmoroz Sep 12, 2024
59ca2a8
reduce number of args functions
vmoroz Sep 13, 2024
da6d540
Merge branch 'main' into pr/node-api-libnode
vmoroz Sep 13, 2024
0f5f9fc
run event loop from UI loop and remove snapshots
vmoroz Sep 17, 2024
e53e166
update API
vmoroz Sep 20, 2024
d261495
add config types
vmoroz Sep 21, 2024
1ce08a1
add status codes and structs
vmoroz Sep 23, 2024
f4b7406
Merge branch 'main' into pr/node-api-libnode
vmoroz Sep 24, 2024
ceaeb11
Merge branch 'main' into pr/node-api-libnode
vmoroz Nov 8, 2024
42e76c8
update API
vmoroz Nov 8, 2024
abfa555
Merge remote-tracking branch 'upstream/main' into pr/node-api-libnode
vmoroz Jan 31, 2025
d895ce1
update embedding API and add C tests
vmoroz Jan 31, 2025
59faec3
update embedding docs
vmoroz Jan 31, 2025
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
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][].
vmoroz marked this conversation as resolved.
Show resolved Hide resolved

Copy link
Member

@mhdawson mhdawson Feb 3, 2025

Choose a reason for hiding this comment

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

Might make sense to say up front that the API is experimental at this point and is not subject to SemVer in respect to changes.

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;
}

Copy link
Member

Choose a reason for hiding this comment

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

Just be before the examples it might be useful to show the steps to get javascript run
I assume something like

  • create platform
  • create runtime
    ..etc

// 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 @@ -6592,6 +6592,145 @@ idempotent.

This API may only be called from the main thread.

## Using embedded Node.js
vmoroz marked this conversation as resolved.
Show resolved Hide resolved

### `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
9 changes: 9 additions & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,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 @@ -222,6 +223,7 @@
'src/module_wrap.h',
'src/node.h',
'src/node_api.h',
'src/node_api_embedding.h',
'src/node_api_types.h',
'src/node_binding.h',
'src/node_blob.h',
Expand Down Expand Up @@ -1285,6 +1287,13 @@
'sources': [
'src/node_snapshot_stub.cc',
'test/embedding/embedtest.cc',
'test/embedding/embedtest_concurrent_node_api.cc',
'test/embedding/embedtest_main.cc',
'test/embedding/embedtest_modules_node_api.cc',
'test/embedding/embedtest_node_api.cc',
'test/embedding/embedtest_node_api.h',
'test/embedding/embedtest_preload_node_api.cc',
'test/embedding/embedtest_snapshot_node_api.cc',
],

'conditions': [
Expand Down
Loading