1# Node-API 2 3<!--introduced_in=v8.0.0--> 4 5<!-- type=misc --> 6 7> Stability: 2 - Stable 8 9Node-API (formerly N-API) is an API for building native Addons. It is 10independent from the underlying JavaScript runtime (for example, V8) and is 11maintained as part of Node.js itself. This API will be Application Binary 12Interface (ABI) stable across versions of Node.js. It is intended to insulate 13addons from changes in the underlying JavaScript engine and allow modules 14compiled for one major version to run on later major versions of Node.js without 15recompilation. The [ABI Stability][] guide provides a more in-depth explanation. 16 17Addons are built/packaged with the same approach/tools outlined in the section 18titled [C++ Addons][]. The only difference is the set of APIs that are used by 19the native code. Instead of using the V8 or [Native Abstractions for Node.js][] 20APIs, the functions available in Node-API are used. 21 22APIs exposed by Node-API are generally used to create and manipulate 23JavaScript values. Concepts and operations generally map to ideas specified 24in the ECMA-262 Language Specification. The APIs have the following 25properties: 26 27* All Node-API calls return a status code of type `napi_status`. This 28 status indicates whether the API call succeeded or failed. 29* The API's return value is passed via an out parameter. 30* All JavaScript values are abstracted behind an opaque type named 31 `napi_value`. 32* In case of an error status code, additional information can be obtained 33 using `napi_get_last_error_info`. More information can be found in the error 34 handling section [Error handling][]. 35 36Node-API is a C API that ensures ABI stability across Node.js versions 37and different compiler levels. A C++ API can be easier to use. 38To support using C++, the project maintains a 39C++ wrapper module called [`node-addon-api`][]. 40This wrapper provides an inlinable C++ API. Binaries built 41with `node-addon-api` will depend on the symbols for the Node-API C-based 42functions exported by Node.js. `node-addon-api` is a more 43efficient way to write code that calls Node-API. Take, for example, the 44following `node-addon-api` code. The first section shows the 45`node-addon-api` code and the second section shows what actually gets 46used in the addon. 47 48```cpp 49Object obj = Object::New(env); 50obj["foo"] = String::New(env, "bar"); 51``` 52 53```cpp 54napi_status status; 55napi_value object, string; 56status = napi_create_object(env, &object); 57if (status != napi_ok) { 58 napi_throw_error(env, ...); 59 return; 60} 61 62status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string); 63if (status != napi_ok) { 64 napi_throw_error(env, ...); 65 return; 66} 67 68status = napi_set_named_property(env, object, "foo", string); 69if (status != napi_ok) { 70 napi_throw_error(env, ...); 71 return; 72} 73``` 74 75The end result is that the addon only uses the exported C APIs. As a result, 76it still gets the benefits of the ABI stability provided by the C API. 77 78When using `node-addon-api` instead of the C APIs, start with the API [docs][] 79for `node-addon-api`. 80 81The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers 82an excellent orientation and tips for developers just getting started with 83Node-API and `node-addon-api`. Additional media resources can be found on the 84[Node-API Media][] page. 85 86## Implications of ABI stability 87 88Although Node-API provides an ABI stability guarantee, other parts of Node.js do 89not, and any external libraries used from the addon may not. In particular, 90none of the following APIs provide an ABI stability guarantee across major 91versions: 92 93* the Node.js C++ APIs available via any of 94 95 ```cpp 96 #include <node.h> 97 #include <node_buffer.h> 98 #include <node_version.h> 99 #include <node_object_wrap.h> 100 ``` 101 102* the libuv APIs which are also included with Node.js and available via 103 104 ```cpp 105 #include <uv.h> 106 ``` 107 108* the V8 API available via 109 110 ```cpp 111 #include <v8.h> 112 ``` 113 114Thus, for an addon to remain ABI-compatible across Node.js major versions, it 115must use Node-API exclusively by restricting itself to using 116 117```c 118#include <node_api.h> 119``` 120 121and by checking, for all external libraries that it uses, that the external 122library makes ABI stability guarantees similar to Node-API. 123 124## Building 125 126Unlike modules written in JavaScript, developing and deploying Node.js 127native addons using Node-API requires an additional set of tools. Besides the 128basic tools required to develop for Node.js, the native addon developer 129requires a toolchain that can compile C and C++ code into a binary. In 130addition, depending upon how the native addon is deployed, the _user_ of 131the native addon will also need to have a C/C++ toolchain installed. 132 133For Linux developers, the necessary C/C++ toolchain packages are readily 134available. [GCC][] is widely used in the Node.js community to build and 135test across a variety of platforms. For many developers, the [LLVM][] 136compiler infrastructure is also a good choice. 137 138For Mac developers, [Xcode][] offers all the required compiler tools. 139However, it is not necessary to install the entire Xcode IDE. The following 140command installs the necessary toolchain: 141 142```bash 143xcode-select --install 144``` 145 146For Windows developers, [Visual Studio][] offers all the required compiler 147tools. However, it is not necessary to install the entire Visual Studio 148IDE. The following command installs the necessary toolchain: 149 150```bash 151npm install --global windows-build-tools 152``` 153 154The sections below describe the additional tools available for developing 155and deploying Node.js native addons. 156 157### Build tools 158 159Both the tools listed here require that _users_ of the native 160addon have a C/C++ toolchain installed in order to successfully install 161the native addon. 162 163#### node-gyp 164 165[node-gyp][] is a build system based on the [gyp-next][] fork of 166Google's [GYP][] tool and comes bundled with npm. GYP, and therefore node-gyp, 167requires that Python be installed. 168 169Historically, node-gyp has been the tool of choice for building native 170addons. It has widespread adoption and documentation. However, some 171developers have run into limitations in node-gyp. 172 173#### CMake.js 174 175[CMake.js][] is an alternative build system based on [CMake][]. 176 177CMake.js is a good choice for projects that already use CMake or for 178developers affected by limitations in node-gyp. [`build_with_cmake`][] is an 179example of a CMake-based native addon project. 180 181### Uploading precompiled binaries 182 183The three tools listed here permit native addon developers and maintainers 184to create and upload binaries to public or private servers. These tools are 185typically integrated with CI/CD build systems like [Travis CI][] and 186[AppVeyor][] to build and upload binaries for a variety of platforms and 187architectures. These binaries are then available for download by users who 188do not need to have a C/C++ toolchain installed. 189 190#### node-pre-gyp 191 192[node-pre-gyp][] is a tool based on node-gyp that adds the ability to 193upload binaries to a server of the developer's choice. node-pre-gyp has 194particularly good support for uploading binaries to Amazon S3. 195 196#### prebuild 197 198[prebuild][] is a tool that supports builds using either node-gyp or 199CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild 200uploads binaries only to [GitHub releases][]. prebuild is a good choice for 201GitHub projects using CMake.js. 202 203#### prebuildify 204 205[prebuildify][] is a tool based on node-gyp. The advantage of prebuildify is 206that the built binaries are bundled with the native addon when it's 207uploaded to npm. The binaries are downloaded from npm and are immediately 208available to the module user when the native addon is installed. 209 210## Usage 211 212In order to use the Node-API functions, include the file [`node_api.h`][] which 213is located in the src directory in the node development tree: 214 215```c 216#include <node_api.h> 217``` 218 219This will opt into the default `NAPI_VERSION` for the given release of Node.js. 220In order to ensure compatibility with specific versions of Node-API, the version 221can be specified explicitly when including the header: 222 223```c 224#define NAPI_VERSION 3 225#include <node_api.h> 226``` 227 228This restricts the Node-API surface to just the functionality that was available 229in the specified (and earlier) versions. 230 231Some of the Node-API surface is experimental and requires explicit opt-in: 232 233```c 234#define NAPI_EXPERIMENTAL 235#include <node_api.h> 236``` 237 238In this case the entire API surface, including any experimental APIs, will be 239available to the module code. 240 241Occasionally, experimental features are introduced that affect already-released 242and stable APIs. These features can be disabled by an opt-out: 243 244```c 245#define NAPI_EXPERIMENTAL 246#define NODE_API_EXPERIMENTAL_<FEATURE_NAME>_OPT_OUT 247#include <node_api.h> 248``` 249 250where `<FEATURE_NAME>` is the name of an experimental feature that affects both 251experimental and stable APIs. 252 253## Node-API version matrix 254 255Node-API versions are additive and versioned independently from Node.js. 256Version 4 is an extension to version 3 in that it has all of the APIs 257from version 3 with some additions. This means that it is not necessary 258to recompile for new versions of Node.js which are 259listed as supporting a later version. 260 261This table may not be up to date in older streams, the most up to date 262information is in the latest API documentation in: 263[Node-API version matrix](https://nodejs.org/docs/latest/api/n-api.html#node-api-version-matrix) 264 265<!-- For accessibility purposes, this table needs row headers. That means we 266 can't do it in markdown. Hence, the raw HTML. --> 267 268<table> 269 <tr> 270 <th>Node-API version</th> 271 <th scope="col">Supported In</th> 272 </tr> 273 <tr> 274 <th scope="row">9</th> 275 <td>v18.17.0+, 20.3.0+, 21.0.0 and all later versions</td> 276 </tr> 277 <tr> 278 <th scope="row">8</th> 279 <td>v12.22.0+, v14.17.0+, v15.12.0+, 16.0.0 and all later versions</td> 280 </tr> 281 <tr> 282 <th scope="row">7</th> 283 <td>v10.23.0+, v12.19.0+, v14.12.0+, 15.0.0 and all later versions</td> 284 </tr> 285 <tr> 286 <th scope="row">6</th> 287 <td>v10.20.0+, v12.17.0+, 14.0.0 and all later versions</td> 288 </tr> 289 <tr> 290 <th scope="row">5</th> 291 <td>v10.17.0+, v12.11.0+, 13.0.0 and all later versions</td> 292 </tr> 293 <tr> 294 <th scope="row">4</th> 295 <td>v10.16.0+, v11.8.0+, 12.0.0 and all later versions</td> 296 </tr> 297 </tr> 298 <tr> 299 <th scope="row">3</th> 300 <td>v6.14.2*, 8.11.2+, v9.11.0+*, 10.0.0 and all later versions</td> 301 </tr> 302 <tr> 303 <th scope="row">2</th> 304 <td>v8.10.0+*, v9.3.0+*, 10.0.0 and all later versions</td> 305 </tr> 306 <tr> 307 <th scope="row">1</th> 308 <td>v8.6.0+**, v9.0.0+*, 10.0.0 and all later versions</td> 309 </tr> 310</table> 311 312\* Node-API was experimental. 313 314\*\* Node.js 8.0.0 included Node-API as experimental. It was released as 315Node-API version 1 but continued to evolve until Node.js 8.6.0. The API is 316different in versions prior to Node.js 8.6.0. We recommend Node-API version 3 or 317later. 318 319Each API documented for Node-API will have a header named `added in:`, and APIs 320which are stable will have the additional header `Node-API version:`. 321APIs are directly usable when using a Node.js version which supports 322the Node-API version shown in `Node-API version:` or higher. 323When using a Node.js version that does not support the 324`Node-API version:` listed or if there is no `Node-API version:` listed, 325then the API will only be available if 326`#define NAPI_EXPERIMENTAL` precedes the inclusion of `node_api.h` 327or `js_native_api.h`. If an API appears not to be available on 328a version of Node.js which is later than the one shown in `added in:` then 329this is most likely the reason for the apparent absence. 330 331The Node-APIs associated strictly with accessing ECMAScript features from native 332code can be found separately in `js_native_api.h` and `js_native_api_types.h`. 333The APIs defined in these headers are included in `node_api.h` and 334`node_api_types.h`. The headers are structured in this way in order to allow 335implementations of Node-API outside of Node.js. For those implementations the 336Node.js specific APIs may not be applicable. 337 338The Node.js-specific parts of an addon can be separated from the code that 339exposes the actual functionality to the JavaScript environment so that the 340latter may be used with multiple implementations of Node-API. In the example 341below, `addon.c` and `addon.h` refer only to `js_native_api.h`. This ensures 342that `addon.c` can be reused to compile against either the Node.js 343implementation of Node-API or any implementation of Node-API outside of Node.js. 344 345`addon_node.c` is a separate file that contains the Node.js specific entry point 346to the addon and which instantiates the addon by calling into `addon.c` when the 347addon is loaded into a Node.js environment. 348 349```c 350// addon.h 351#ifndef _ADDON_H_ 352#define _ADDON_H_ 353#include <js_native_api.h> 354napi_value create_addon(napi_env env); 355#endif // _ADDON_H_ 356``` 357 358```c 359// addon.c 360#include "addon.h" 361 362#define NODE_API_CALL(env, call) \ 363 do { \ 364 napi_status status = (call); \ 365 if (status != napi_ok) { \ 366 const napi_extended_error_info* error_info = NULL; \ 367 napi_get_last_error_info((env), &error_info); \ 368 const char* err_message = error_info->error_message; \ 369 bool is_pending; \ 370 napi_is_exception_pending((env), &is_pending); \ 371 /* If an exception is already pending, don't rethrow it */ \ 372 if (!is_pending) { \ 373 const char* message = (err_message == NULL) \ 374 ? "empty error message" \ 375 : err_message; \ 376 napi_throw_error((env), NULL, message); \ 377 } \ 378 return NULL; \ 379 } \ 380 } while(0) 381 382static napi_value 383DoSomethingUseful(napi_env env, napi_callback_info info) { 384 // Do something useful. 385 return NULL; 386} 387 388napi_value create_addon(napi_env env) { 389 napi_value result; 390 NODE_API_CALL(env, napi_create_object(env, &result)); 391 392 napi_value exported_function; 393 NODE_API_CALL(env, napi_create_function(env, 394 "doSomethingUseful", 395 NAPI_AUTO_LENGTH, 396 DoSomethingUseful, 397 NULL, 398 &exported_function)); 399 400 NODE_API_CALL(env, napi_set_named_property(env, 401 result, 402 "doSomethingUseful", 403 exported_function)); 404 405 return result; 406} 407``` 408 409```c 410// addon_node.c 411#include <node_api.h> 412#include "addon.h" 413 414NAPI_MODULE_INIT(/* napi_env env, napi_value exports */) { 415 // This function body is expected to return a `napi_value`. 416 // The variables `napi_env env` and `napi_value exports` may be used within 417 // the body, as they are provided by the definition of `NAPI_MODULE_INIT()`. 418 return create_addon(env); 419} 420``` 421 422## Environment life cycle APIs 423 424[Section 8.7][] of the [ECMAScript Language Specification][] defines the concept 425of an "Agent" as a self-contained environment in which JavaScript code runs. 426Multiple such Agents may be started and terminated either concurrently or in 427sequence by the process. 428 429A Node.js environment corresponds to an ECMAScript Agent. In the main process, 430an environment is created at startup, and additional environments can be created 431on separate threads to serve as [worker threads][]. When Node.js is embedded in 432another application, the main thread of the application may also construct and 433destroy a Node.js environment multiple times during the life cycle of the 434application process such that each Node.js environment created by the 435application may, in turn, during its life cycle create and destroy additional 436environments as worker threads. 437 438From the perspective of a native addon this means that the bindings it provides 439may be called multiple times, from multiple contexts, and even concurrently from 440multiple threads. 441 442Native addons may need to allocate global state which they use during 443their life cycle of an Node.js environment such that the state can be 444unique to each instance of the addon. 445 446To this end, Node-API provides a way to associate data such that its life cycle 447is tied to the life cycle of a Node.js environment. 448 449### `napi_set_instance_data` 450 451<!-- YAML 452added: 453 - v12.8.0 454 - v10.20.0 455napiVersion: 6 456--> 457 458```c 459napi_status napi_set_instance_data(node_api_nogc_env env, 460 void* data, 461 napi_finalize finalize_cb, 462 void* finalize_hint); 463``` 464 465* `[in] env`: The environment that the Node-API call is invoked under. 466* `[in] data`: The data item to make available to bindings of this instance. 467* `[in] finalize_cb`: The function to call when the environment is being torn 468 down. The function receives `data` so that it might free it. 469 [`napi_finalize`][] provides more details. 470* `[in] finalize_hint`: Optional hint to pass to the finalize callback during 471 collection. 472 473Returns `napi_ok` if the API succeeded. 474 475This API associates `data` with the currently running Node.js environment. `data` 476can later be retrieved using `napi_get_instance_data()`. Any existing data 477associated with the currently running Node.js environment which was set by means 478of a previous call to `napi_set_instance_data()` will be overwritten. If a 479`finalize_cb` was provided by the previous call, it will not be called. 480 481### `napi_get_instance_data` 482 483<!-- YAML 484added: 485 - v12.8.0 486 - v10.20.0 487napiVersion: 6 488--> 489 490```c 491napi_status napi_get_instance_data(node_api_nogc_env env, 492 void** data); 493``` 494 495* `[in] env`: The environment that the Node-API call is invoked under. 496* `[out] data`: The data item that was previously associated with the currently 497 running Node.js environment by a call to `napi_set_instance_data()`. 498 499Returns `napi_ok` if the API succeeded. 500 501This API retrieves data that was previously associated with the currently 502running Node.js environment via `napi_set_instance_data()`. If no data is set, 503the call will succeed and `data` will be set to `NULL`. 504 505## Basic Node-API data types 506 507Node-API exposes the following fundamental data types as abstractions that are 508consumed by the various APIs. These APIs should be treated as opaque, 509introspectable only with other Node-API calls. 510 511### `napi_status` 512 513<!-- YAML 514added: v8.0.0 515napiVersion: 1 516--> 517 518Integral status code indicating the success or failure of a Node-API call. 519Currently, the following status codes are supported. 520 521```c 522typedef enum { 523 napi_ok, 524 napi_invalid_arg, 525 napi_object_expected, 526 napi_string_expected, 527 napi_name_expected, 528 napi_function_expected, 529 napi_number_expected, 530 napi_boolean_expected, 531 napi_array_expected, 532 napi_generic_failure, 533 napi_pending_exception, 534 napi_cancelled, 535 napi_escape_called_twice, 536 napi_handle_scope_mismatch, 537 napi_callback_scope_mismatch, 538 napi_queue_full, 539 napi_closing, 540 napi_bigint_expected, 541 napi_date_expected, 542 napi_arraybuffer_expected, 543 napi_detachable_arraybuffer_expected, 544 napi_would_deadlock, /* unused */ 545 napi_no_external_buffers_allowed, 546 napi_cannot_run_js 547} napi_status; 548``` 549 550If additional information is required upon an API returning a failed status, 551it can be obtained by calling `napi_get_last_error_info`. 552 553### `napi_extended_error_info` 554 555<!-- YAML 556added: v8.0.0 557napiVersion: 1 558--> 559 560```c 561typedef struct { 562 const char* error_message; 563 void* engine_reserved; 564 uint32_t engine_error_code; 565 napi_status error_code; 566} napi_extended_error_info; 567``` 568 569* `error_message`: UTF8-encoded string containing a VM-neutral description of 570 the error. 571* `engine_reserved`: Reserved for VM-specific error details. This is currently 572 not implemented for any VM. 573* `engine_error_code`: VM-specific error code. This is currently 574 not implemented for any VM. 575* `error_code`: The Node-API status code that originated with the last error. 576 577See the [Error handling][] section for additional information. 578 579### `napi_env` 580 581`napi_env` is used to represent a context that the underlying Node-API 582implementation can use to persist VM-specific state. This structure is passed 583to native functions when they're invoked, and it must be passed back when 584making Node-API calls. Specifically, the same `napi_env` that was passed in when 585the initial native function was called must be passed to any subsequent 586nested Node-API calls. Caching the `napi_env` for the purpose of general reuse, 587and passing the `napi_env` between instances of the same addon running on 588different [`Worker`][] threads is not allowed. The `napi_env` becomes invalid 589when an instance of a native addon is unloaded. Notification of this event is 590delivered through the callbacks given to [`napi_add_env_cleanup_hook`][] and 591[`napi_set_instance_data`][]. 592 593### `node_api_nogc_env` 594 595> Stability: 1 - Experimental 596 597This variant of `napi_env` is passed to synchronous finalizers 598([`node_api_nogc_finalize`][]). There is a subset of Node-APIs which accept 599a parameter of type `node_api_nogc_env` as their first argument. These APIs do 600not access the state of the JavaScript engine and are thus safe to call from 601synchronous finalizers. Passing a parameter of type `napi_env` to these APIs is 602allowed, however, passing a parameter of type `node_api_nogc_env` to APIs that 603access the JavaScript engine state is not allowed. Attempting to do so without 604a cast will produce a compiler warning or an error when add-ons are compiled 605with flags which cause them to emit warnings and/or errors when incorrect 606pointer types are passed into a function. Calling such APIs from a synchronous 607finalizer will ultimately result in the termination of the application. 608 609### `napi_value` 610 611This is an opaque pointer that is used to represent a JavaScript value. 612 613### `napi_threadsafe_function` 614 615<!-- YAML 616added: v10.6.0 617napiVersion: 4 618--> 619 620This is an opaque pointer that represents a JavaScript function which can be 621called asynchronously from multiple threads via 622`napi_call_threadsafe_function()`. 623 624### `napi_threadsafe_function_release_mode` 625 626<!-- YAML 627added: v10.6.0 628napiVersion: 4 629--> 630 631A value to be given to `napi_release_threadsafe_function()` to indicate whether 632the thread-safe function is to be closed immediately (`napi_tsfn_abort`) or 633merely released (`napi_tsfn_release`) and thus available for subsequent use via 634`napi_acquire_threadsafe_function()` and `napi_call_threadsafe_function()`. 635 636```c 637typedef enum { 638 napi_tsfn_release, 639 napi_tsfn_abort 640} napi_threadsafe_function_release_mode; 641``` 642 643### `napi_threadsafe_function_call_mode` 644 645<!-- YAML 646added: v10.6.0 647napiVersion: 4 648--> 649 650A value to be given to `napi_call_threadsafe_function()` to indicate whether 651the call should block whenever the queue associated with the thread-safe 652function is full. 653 654```c 655typedef enum { 656 napi_tsfn_nonblocking, 657 napi_tsfn_blocking 658} napi_threadsafe_function_call_mode; 659``` 660 661### Node-API memory management types 662 663#### `napi_handle_scope` 664 665This is an abstraction used to control and modify the lifetime of objects 666created within a particular scope. In general, Node-API values are created 667within the context of a handle scope. When a native method is called from 668JavaScript, a default handle scope will exist. If the user does not explicitly 669create a new handle scope, Node-API values will be created in the default handle 670scope. For any invocations of code outside the execution of a native method 671(for instance, during a libuv callback invocation), the module is required to 672create a scope before invoking any functions that can result in the creation 673of JavaScript values. 674 675Handle scopes are created using [`napi_open_handle_scope`][] and are destroyed 676using [`napi_close_handle_scope`][]. Closing the scope can indicate to the GC 677that all `napi_value`s created during the lifetime of the handle scope are no 678longer referenced from the current stack frame. 679 680For more details, review the [Object lifetime management][]. 681 682#### `napi_escapable_handle_scope` 683 684<!-- YAML 685added: v8.0.0 686napiVersion: 1 687--> 688 689Escapable handle scopes are a special type of handle scope to return values 690created within a particular handle scope to a parent scope. 691 692#### `napi_ref` 693 694<!-- YAML 695added: v8.0.0 696napiVersion: 1 697--> 698 699This is the abstraction to use to reference a `napi_value`. This allows for 700users to manage the lifetimes of JavaScript values, including defining their 701minimum lifetimes explicitly. 702 703For more details, review the [Object lifetime management][]. 704 705#### `napi_type_tag` 706 707<!-- YAML 708added: 709 - v14.8.0 710 - v12.19.0 711napiVersion: 8 712--> 713 714A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID 715with which JavaScript objects or [externals][] can be "tagged" in order to 716ensure that they are of a certain type. This is a stronger check than 717[`napi_instanceof`][], because the latter can report a false positive if the 718object's prototype has been manipulated. Type-tagging is most useful in 719conjunction with [`napi_wrap`][] because it ensures that the pointer retrieved 720from a wrapped object can be safely cast to the native type corresponding to the 721type tag that had been previously applied to the JavaScript object. 722 723```c 724typedef struct { 725 uint64_t lower; 726 uint64_t upper; 727} napi_type_tag; 728``` 729 730#### `napi_async_cleanup_hook_handle` 731 732<!-- YAML 733added: 734 - v14.10.0 735 - v12.19.0 736--> 737 738An opaque value returned by [`napi_add_async_cleanup_hook`][]. It must be passed 739to [`napi_remove_async_cleanup_hook`][] when the chain of asynchronous cleanup 740events completes. 741 742### Node-API callback types 743 744#### `napi_callback_info` 745 746<!-- YAML 747added: v8.0.0 748napiVersion: 1 749--> 750 751Opaque datatype that is passed to a callback function. It can be used for 752getting additional information about the context in which the callback was 753invoked. 754 755#### `napi_callback` 756 757<!-- YAML 758added: v8.0.0 759napiVersion: 1 760--> 761 762Function pointer type for user-provided native functions which are to be 763exposed to JavaScript via Node-API. Callback functions should satisfy the 764following signature: 765 766```c 767typedef napi_value (*napi_callback)(napi_env, napi_callback_info); 768``` 769 770Unless for reasons discussed in [Object Lifetime Management][], creating a 771handle and/or callback scope inside a `napi_callback` is not necessary. 772 773#### `node_api_nogc_finalize` 774 775<!-- YAML 776added: v18.20.0 777--> 778 779> Stability: 1 - Experimental 780 781Function pointer type for add-on provided functions that allow the user to be 782notified when externally-owned data is ready to be cleaned up because the 783object it was associated with has been garbage-collected. The user must provide 784a function satisfying the following signature which would get called upon the 785object's collection. Currently, `node_api_nogc_finalize` can be used for 786finding out when objects that have external data are collected. 787 788```c 789typedef void (*node_api_nogc_finalize)(node_api_nogc_env env, 790 void* finalize_data, 791 void* finalize_hint); 792``` 793 794Unless for reasons discussed in [Object Lifetime Management][], creating a 795handle and/or callback scope inside the function body is not necessary. 796 797Since these functions may be called while the JavaScript engine is in a state 798where it cannot execute JavaScript code, only Node-APIs which accept a 799`node_api_nogc_env` as their first parameter may be called. 800[`node_api_post_finalizer`][] can be used to schedule Node-API calls that 801require access to the JavaScript engine's state to run after the current 802garbage collection cycle has completed. 803 804In the case of [`node_api_create_external_string_latin1`][] and 805[`node_api_create_external_string_utf16`][] the `env` parameter may be null, 806because external strings can be collected during the latter part of environment 807shutdown. 808 809Change History: 810 811* experimental (`NAPI_EXPERIMENTAL`): 812 813 Only Node-API calls that accept a `node_api_nogc_env` as their first 814 parameter may be called, otherwise the application will be terminated with an 815 appropriate error message. This feature can be turned off by defining 816 `NODE_API_EXPERIMENTAL_NOGC_ENV_OPT_OUT`. 817 818#### `napi_finalize` 819 820<!-- YAML 821added: v8.0.0 822napiVersion: 1 823--> 824 825Function pointer type for add-on provided function that allow the user to 826schedule a group of calls to Node-APIs in response to a garbage collection 827event, after the garbage collection cycle has completed. These function 828pointers can be used with [`node_api_post_finalizer`][]. 829 830```c 831typedef void (*napi_finalize)(napi_env env, 832 void* finalize_data, 833 void* finalize_hint); 834``` 835 836Change History: 837 838* experimental (`NAPI_EXPERIMENTAL` is defined): 839 840 A function of this type may no longer be used as a finalizer, except with 841 [`node_api_post_finalizer`][]. [`node_api_nogc_finalize`][] must be used 842 instead. This feature can be turned off by defining 843 `NODE_API_EXPERIMENTAL_NOGC_ENV_OPT_OUT`. 844 845#### `napi_async_execute_callback` 846 847<!-- YAML 848added: v8.0.0 849napiVersion: 1 850--> 851 852Function pointer used with functions that support asynchronous 853operations. Callback functions must satisfy the following signature: 854 855```c 856typedef void (*napi_async_execute_callback)(napi_env env, void* data); 857``` 858 859Implementations of this function must avoid making Node-API calls that execute 860JavaScript or interact with JavaScript objects. Node-API calls should be in the 861`napi_async_complete_callback` instead. Do not use the `napi_env` parameter as 862it will likely result in execution of JavaScript. 863 864#### `napi_async_complete_callback` 865 866<!-- YAML 867added: v8.0.0 868napiVersion: 1 869--> 870 871Function pointer used with functions that support asynchronous 872operations. Callback functions must satisfy the following signature: 873 874```c 875typedef void (*napi_async_complete_callback)(napi_env env, 876 napi_status status, 877 void* data); 878``` 879 880Unless for reasons discussed in [Object Lifetime Management][], creating a 881handle and/or callback scope inside the function body is not necessary. 882 883#### `napi_threadsafe_function_call_js` 884 885<!-- YAML 886added: v10.6.0 887napiVersion: 4 888--> 889 890Function pointer used with asynchronous thread-safe function calls. The callback 891will be called on the main thread. Its purpose is to use a data item arriving 892via the queue from one of the secondary threads to construct the parameters 893necessary for a call into JavaScript, usually via `napi_call_function`, and then 894make the call into JavaScript. 895 896The data arriving from the secondary thread via the queue is given in the `data` 897parameter and the JavaScript function to call is given in the `js_callback` 898parameter. 899 900Node-API sets up the environment prior to calling this callback, so it is 901sufficient to call the JavaScript function via `napi_call_function` rather than 902via `napi_make_callback`. 903 904Callback functions must satisfy the following signature: 905 906```c 907typedef void (*napi_threadsafe_function_call_js)(napi_env env, 908 napi_value js_callback, 909 void* context, 910 void* data); 911``` 912 913* `[in] env`: The environment to use for API calls, or `NULL` if the thread-safe 914 function is being torn down and `data` may need to be freed. 915* `[in] js_callback`: The JavaScript function to call, or `NULL` if the 916 thread-safe function is being torn down and `data` may need to be freed. It 917 may also be `NULL` if the thread-safe function was created without 918 `js_callback`. 919* `[in] context`: The optional data with which the thread-safe function was 920 created. 921* `[in] data`: Data created by the secondary thread. It is the responsibility of 922 the callback to convert this native data to JavaScript values (with Node-API 923 functions) that can be passed as parameters when `js_callback` is invoked. 924 This pointer is managed entirely by the threads and this callback. Thus this 925 callback should free the data. 926 927Unless for reasons discussed in [Object Lifetime Management][], creating a 928handle and/or callback scope inside the function body is not necessary. 929 930#### `napi_cleanup_hook` 931 932<!-- YAML 933added: v18.13.0 934napiVersion: 3 935--> 936 937Function pointer used with [`napi_add_env_cleanup_hook`][]. It will be called 938when the environment is being torn down. 939 940Callback functions must satisfy the following signature: 941 942```c 943typedef void (*napi_cleanup_hook)(void* data); 944``` 945 946* `[in] data`: The data that was passed to [`napi_add_env_cleanup_hook`][]. 947 948#### `napi_async_cleanup_hook` 949 950<!-- YAML 951added: 952 - v14.10.0 953 - v12.19.0 954--> 955 956Function pointer used with [`napi_add_async_cleanup_hook`][]. It will be called 957when the environment is being torn down. 958 959Callback functions must satisfy the following signature: 960 961```c 962typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle, 963 void* data); 964``` 965 966* `[in] handle`: The handle that must be passed to 967 [`napi_remove_async_cleanup_hook`][] after completion of the asynchronous 968 cleanup. 969* `[in] data`: The data that was passed to [`napi_add_async_cleanup_hook`][]. 970 971The body of the function should initiate the asynchronous cleanup actions at the 972end of which `handle` must be passed in a call to 973[`napi_remove_async_cleanup_hook`][]. 974 975## Error handling 976 977Node-API uses both return values and JavaScript exceptions for error handling. 978The following sections explain the approach for each case. 979 980### Return values 981 982All of the Node-API functions share the same error handling pattern. The 983return type of all API functions is `napi_status`. 984 985The return value will be `napi_ok` if the request was successful and 986no uncaught JavaScript exception was thrown. If an error occurred AND 987an exception was thrown, the `napi_status` value for the error 988will be returned. If an exception was thrown, and no error occurred, 989`napi_pending_exception` will be returned. 990 991In cases where a return value other than `napi_ok` or 992`napi_pending_exception` is returned, [`napi_is_exception_pending`][] 993must be called to check if an exception is pending. 994See the section on exceptions for more details. 995 996The full set of possible `napi_status` values is defined 997in `napi_api_types.h`. 998 999The `napi_status` return value provides a VM-independent representation of 1000the error which occurred. In some cases it is useful to be able to get 1001more detailed information, including a string representing the error as well as 1002VM (engine)-specific information. 1003 1004In order to retrieve this information [`napi_get_last_error_info`][] 1005is provided which returns a `napi_extended_error_info` structure. 1006The format of the `napi_extended_error_info` structure is as follows: 1007 1008<!-- YAML 1009added: v8.0.0 1010napiVersion: 1 1011--> 1012 1013```c 1014typedef struct napi_extended_error_info { 1015 const char* error_message; 1016 void* engine_reserved; 1017 uint32_t engine_error_code; 1018 napi_status error_code; 1019}; 1020``` 1021 1022* `error_message`: Textual representation of the error that occurred. 1023* `engine_reserved`: Opaque handle reserved for engine use only. 1024* `engine_error_code`: VM specific error code. 1025* `error_code`: Node-API status code for the last error. 1026 1027[`napi_get_last_error_info`][] returns the information for the last 1028Node-API call that was made. 1029 1030Do not rely on the content or format of any of the extended information as it 1031is not subject to SemVer and may change at any time. It is intended only for 1032logging purposes. 1033 1034#### `napi_get_last_error_info` 1035 1036<!-- YAML 1037added: v8.0.0 1038napiVersion: 1 1039--> 1040 1041```c 1042napi_status 1043napi_get_last_error_info(node_api_nogc_env env, 1044 const napi_extended_error_info** result); 1045``` 1046 1047* `[in] env`: The environment that the API is invoked under. 1048* `[out] result`: The `napi_extended_error_info` structure with more 1049 information about the error. 1050 1051Returns `napi_ok` if the API succeeded. 1052 1053This API retrieves a `napi_extended_error_info` structure with information 1054about the last error that occurred. 1055 1056The content of the `napi_extended_error_info` returned is only valid up until 1057a Node-API function is called on the same `env`. This includes a call to 1058`napi_is_exception_pending` so it may often be necessary to make a copy 1059of the information so that it can be used later. The pointer returned 1060in `error_message` points to a statically-defined string so it is safe to use 1061that pointer if you have copied it out of the `error_message` field (which will 1062be overwritten) before another Node-API function was called. 1063 1064Do not rely on the content or format of any of the extended information as it 1065is not subject to SemVer and may change at any time. It is intended only for 1066logging purposes. 1067 1068This API can be called even if there is a pending JavaScript exception. 1069 1070### Exceptions 1071 1072Any Node-API function call may result in a pending JavaScript exception. This is 1073the case for any of the API functions, even those that may not cause the 1074execution of JavaScript. 1075 1076If the `napi_status` returned by a function is `napi_ok` then no 1077exception is pending and no additional action is required. If the 1078`napi_status` returned is anything other than `napi_ok` or 1079`napi_pending_exception`, in order to try to recover and continue 1080instead of simply returning immediately, [`napi_is_exception_pending`][] 1081must be called in order to determine if an exception is pending or not. 1082 1083In many cases when a Node-API function is called and an exception is 1084already pending, the function will return immediately with a 1085`napi_status` of `napi_pending_exception`. However, this is not the case 1086for all functions. Node-API allows a subset of the functions to be 1087called to allow for some minimal cleanup before returning to JavaScript. 1088In that case, `napi_status` will reflect the status for the function. It 1089will not reflect previous pending exceptions. To avoid confusion, check 1090the error status after every function call. 1091 1092When an exception is pending one of two approaches can be employed. 1093 1094The first approach is to do any appropriate cleanup and then return so that 1095execution will return to JavaScript. As part of the transition back to 1096JavaScript, the exception will be thrown at the point in the JavaScript 1097code where the native method was invoked. The behavior of most Node-API calls 1098is unspecified while an exception is pending, and many will simply return 1099`napi_pending_exception`, so do as little as possible and then return to 1100JavaScript where the exception can be handled. 1101 1102The second approach is to try to handle the exception. There will be cases 1103where the native code can catch the exception, take the appropriate action, 1104and then continue. This is only recommended in specific cases 1105where it is known that the exception can be safely handled. In these 1106cases [`napi_get_and_clear_last_exception`][] can be used to get and 1107clear the exception. On success, result will contain the handle to 1108the last JavaScript `Object` thrown. If it is determined, after 1109retrieving the exception, the exception cannot be handled after all 1110it can be re-thrown it with [`napi_throw`][] where error is the 1111JavaScript value to be thrown. 1112 1113The following utility functions are also available in case native code 1114needs to throw an exception or determine if a `napi_value` is an instance 1115of a JavaScript `Error` object: [`napi_throw_error`][], 1116[`napi_throw_type_error`][], [`napi_throw_range_error`][], [`node_api_throw_syntax_error`][] and [`napi_is_error`][]. 1117 1118The following utility functions are also available in case native 1119code needs to create an `Error` object: [`napi_create_error`][], 1120[`napi_create_type_error`][], [`napi_create_range_error`][] and [`node_api_create_syntax_error`][], 1121where result is the `napi_value` that refers to the newly created 1122JavaScript `Error` object. 1123 1124The Node.js project is adding error codes to all of the errors 1125generated internally. The goal is for applications to use these 1126error codes for all error checking. The associated error messages 1127will remain, but will only be meant to be used for logging and 1128display with the expectation that the message can change without 1129SemVer applying. In order to support this model with Node-API, both 1130in internal functionality and for module specific functionality 1131(as its good practice), the `throw_` and `create_` functions 1132take an optional code parameter which is the string for the code 1133to be added to the error object. If the optional parameter is `NULL` 1134then no code will be associated with the error. If a code is provided, 1135the name associated with the error is also updated to be: 1136 1137```text 1138originalName [code] 1139``` 1140 1141where `originalName` is the original name associated with the error 1142and `code` is the code that was provided. For example, if the code 1143is `'ERR_ERROR_1'` and a `TypeError` is being created the name will be: 1144 1145```text 1146TypeError [ERR_ERROR_1] 1147``` 1148 1149#### `napi_throw` 1150 1151<!-- YAML 1152added: v8.0.0 1153napiVersion: 1 1154--> 1155 1156```c 1157NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error); 1158``` 1159 1160* `[in] env`: The environment that the API is invoked under. 1161* `[in] error`: The JavaScript value to be thrown. 1162 1163Returns `napi_ok` if the API succeeded. 1164 1165This API throws the JavaScript value provided. 1166 1167#### `napi_throw_error` 1168 1169<!-- YAML 1170added: v8.0.0 1171napiVersion: 1 1172--> 1173 1174```c 1175NAPI_EXTERN napi_status napi_throw_error(napi_env env, 1176 const char* code, 1177 const char* msg); 1178``` 1179 1180* `[in] env`: The environment that the API is invoked under. 1181* `[in] code`: Optional error code to be set on the error. 1182* `[in] msg`: C string representing the text to be associated with the error. 1183 1184Returns `napi_ok` if the API succeeded. 1185 1186This API throws a JavaScript `Error` with the text provided. 1187 1188#### `napi_throw_type_error` 1189 1190<!-- YAML 1191added: v8.0.0 1192napiVersion: 1 1193--> 1194 1195```c 1196NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, 1197 const char* code, 1198 const char* msg); 1199``` 1200 1201* `[in] env`: The environment that the API is invoked under. 1202* `[in] code`: Optional error code to be set on the error. 1203* `[in] msg`: C string representing the text to be associated with the error. 1204 1205Returns `napi_ok` if the API succeeded. 1206 1207This API throws a JavaScript `TypeError` with the text provided. 1208 1209#### `napi_throw_range_error` 1210 1211<!-- YAML 1212added: v8.0.0 1213napiVersion: 1 1214--> 1215 1216```c 1217NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, 1218 const char* code, 1219 const char* msg); 1220``` 1221 1222* `[in] env`: The environment that the API is invoked under. 1223* `[in] code`: Optional error code to be set on the error. 1224* `[in] msg`: C string representing the text to be associated with the error. 1225 1226Returns `napi_ok` if the API succeeded. 1227 1228This API throws a JavaScript `RangeError` with the text provided. 1229 1230#### `node_api_throw_syntax_error` 1231 1232<!-- YAML 1233added: 1234 - v17.2.0 1235 - v16.14.0 1236napiVersion: 9 1237--> 1238 1239```c 1240NAPI_EXTERN napi_status node_api_throw_syntax_error(napi_env env, 1241 const char* code, 1242 const char* msg); 1243``` 1244 1245* `[in] env`: The environment that the API is invoked under. 1246* `[in] code`: Optional error code to be set on the error. 1247* `[in] msg`: C string representing the text to be associated with the error. 1248 1249Returns `napi_ok` if the API succeeded. 1250 1251This API throws a JavaScript `SyntaxError` with the text provided. 1252 1253#### `napi_is_error` 1254 1255<!-- YAML 1256added: v8.0.0 1257napiVersion: 1 1258--> 1259 1260```c 1261NAPI_EXTERN napi_status napi_is_error(napi_env env, 1262 napi_value value, 1263 bool* result); 1264``` 1265 1266* `[in] env`: The environment that the API is invoked under. 1267* `[in] value`: The `napi_value` to be checked. 1268* `[out] result`: Boolean value that is set to true if `napi_value` represents 1269 an error, false otherwise. 1270 1271Returns `napi_ok` if the API succeeded. 1272 1273This API queries a `napi_value` to check if it represents an error object. 1274 1275#### `napi_create_error` 1276 1277<!-- YAML 1278added: v8.0.0 1279napiVersion: 1 1280--> 1281 1282```c 1283NAPI_EXTERN napi_status napi_create_error(napi_env env, 1284 napi_value code, 1285 napi_value msg, 1286 napi_value* result); 1287``` 1288 1289* `[in] env`: The environment that the API is invoked under. 1290* `[in] code`: Optional `napi_value` with the string for the error code to be 1291 associated with the error. 1292* `[in] msg`: `napi_value` that references a JavaScript `string` to be used as 1293 the message for the `Error`. 1294* `[out] result`: `napi_value` representing the error created. 1295 1296Returns `napi_ok` if the API succeeded. 1297 1298This API returns a JavaScript `Error` with the text provided. 1299 1300#### `napi_create_type_error` 1301 1302<!-- YAML 1303added: v8.0.0 1304napiVersion: 1 1305--> 1306 1307```c 1308NAPI_EXTERN napi_status napi_create_type_error(napi_env env, 1309 napi_value code, 1310 napi_value msg, 1311 napi_value* result); 1312``` 1313 1314* `[in] env`: The environment that the API is invoked under. 1315* `[in] code`: Optional `napi_value` with the string for the error code to be 1316 associated with the error. 1317* `[in] msg`: `napi_value` that references a JavaScript `string` to be used as 1318 the message for the `Error`. 1319* `[out] result`: `napi_value` representing the error created. 1320 1321Returns `napi_ok` if the API succeeded. 1322 1323This API returns a JavaScript `TypeError` with the text provided. 1324 1325#### `napi_create_range_error` 1326 1327<!-- YAML 1328added: v8.0.0 1329napiVersion: 1 1330--> 1331 1332```c 1333NAPI_EXTERN napi_status napi_create_range_error(napi_env env, 1334 napi_value code, 1335 napi_value msg, 1336 napi_value* result); 1337``` 1338 1339* `[in] env`: The environment that the API is invoked under. 1340* `[in] code`: Optional `napi_value` with the string for the error code to be 1341 associated with the error. 1342* `[in] msg`: `napi_value` that references a JavaScript `string` to be used as 1343 the message for the `Error`. 1344* `[out] result`: `napi_value` representing the error created. 1345 1346Returns `napi_ok` if the API succeeded. 1347 1348This API returns a JavaScript `RangeError` with the text provided. 1349 1350#### `node_api_create_syntax_error` 1351 1352<!-- YAML 1353added: 1354 - v17.2.0 1355 - v16.14.0 1356napiVersion: 9 1357--> 1358 1359```c 1360NAPI_EXTERN napi_status node_api_create_syntax_error(napi_env env, 1361 napi_value code, 1362 napi_value msg, 1363 napi_value* result); 1364``` 1365 1366* `[in] env`: The environment that the API is invoked under. 1367* `[in] code`: Optional `napi_value` with the string for the error code to be 1368 associated with the error. 1369* `[in] msg`: `napi_value` that references a JavaScript `string` to be used as 1370 the message for the `Error`. 1371* `[out] result`: `napi_value` representing the error created. 1372 1373Returns `napi_ok` if the API succeeded. 1374 1375This API returns a JavaScript `SyntaxError` with the text provided. 1376 1377#### `napi_get_and_clear_last_exception` 1378 1379<!-- YAML 1380added: v8.0.0 1381napiVersion: 1 1382--> 1383 1384```c 1385napi_status napi_get_and_clear_last_exception(napi_env env, 1386 napi_value* result); 1387``` 1388 1389* `[in] env`: The environment that the API is invoked under. 1390* `[out] result`: The exception if one is pending, `NULL` otherwise. 1391 1392Returns `napi_ok` if the API succeeded. 1393 1394This API can be called even if there is a pending JavaScript exception. 1395 1396#### `napi_is_exception_pending` 1397 1398<!-- YAML 1399added: v8.0.0 1400napiVersion: 1 1401--> 1402 1403```c 1404napi_status napi_is_exception_pending(napi_env env, bool* result); 1405``` 1406 1407* `[in] env`: The environment that the API is invoked under. 1408* `[out] result`: Boolean value that is set to true if an exception is pending. 1409 1410Returns `napi_ok` if the API succeeded. 1411 1412This API can be called even if there is a pending JavaScript exception. 1413 1414#### `napi_fatal_exception` 1415 1416<!-- YAML 1417added: v9.10.0 1418napiVersion: 3 1419--> 1420 1421```c 1422napi_status napi_fatal_exception(napi_env env, napi_value err); 1423``` 1424 1425* `[in] env`: The environment that the API is invoked under. 1426* `[in] err`: The error that is passed to `'uncaughtException'`. 1427 1428Trigger an `'uncaughtException'` in JavaScript. Useful if an async 1429callback throws an exception with no way to recover. 1430 1431### Fatal errors 1432 1433In the event of an unrecoverable error in a native addon, a fatal error can be 1434thrown to immediately terminate the process. 1435 1436#### `napi_fatal_error` 1437 1438<!-- YAML 1439added: v8.2.0 1440napiVersion: 1 1441--> 1442 1443```c 1444NAPI_NO_RETURN void napi_fatal_error(const char* location, 1445 size_t location_len, 1446 const char* message, 1447 size_t message_len); 1448``` 1449 1450* `[in] location`: Optional location at which the error occurred. 1451* `[in] location_len`: The length of the location in bytes, or 1452 `NAPI_AUTO_LENGTH` if it is null-terminated. 1453* `[in] message`: The message associated with the error. 1454* `[in] message_len`: The length of the message in bytes, or `NAPI_AUTO_LENGTH` 1455 if it is null-terminated. 1456 1457The function call does not return, the process will be terminated. 1458 1459This API can be called even if there is a pending JavaScript exception. 1460 1461## Object lifetime management 1462 1463As Node-API calls are made, handles to objects in the heap for the underlying 1464VM may be returned as `napi_values`. These handles must hold the 1465objects 'live' until they are no longer required by the native code, 1466otherwise the objects could be collected before the native code was 1467finished using them. 1468 1469As object handles are returned they are associated with a 1470'scope'. The lifespan for the default scope is tied to the lifespan 1471of the native method call. The result is that, by default, handles 1472remain valid and the objects associated with these handles will be 1473held live for the lifespan of the native method call. 1474 1475In many cases, however, it is necessary that the handles remain valid for 1476either a shorter or longer lifespan than that of the native method. 1477The sections which follow describe the Node-API functions that can be used 1478to change the handle lifespan from the default. 1479 1480### Making handle lifespan shorter than that of the native method 1481 1482It is often necessary to make the lifespan of handles shorter than 1483the lifespan of a native method. For example, consider a native method 1484that has a loop which iterates through the elements in a large array: 1485 1486```c 1487for (int i = 0; i < 1000000; i++) { 1488 napi_value result; 1489 napi_status status = napi_get_element(env, object, i, &result); 1490 if (status != napi_ok) { 1491 break; 1492 } 1493 // do something with element 1494} 1495``` 1496 1497This would result in a large number of handles being created, consuming 1498substantial resources. In addition, even though the native code could only 1499use the most recent handle, all of the associated objects would also be 1500kept alive since they all share the same scope. 1501 1502To handle this case, Node-API provides the ability to establish a new 'scope' to 1503which newly created handles will be associated. Once those handles 1504are no longer required, the scope can be 'closed' and any handles associated 1505with the scope are invalidated. The methods available to open/close scopes are 1506[`napi_open_handle_scope`][] and [`napi_close_handle_scope`][]. 1507 1508Node-API only supports a single nested hierarchy of scopes. There is only one 1509active scope at any time, and all new handles will be associated with that 1510scope while it is active. Scopes must be closed in the reverse order from 1511which they are opened. In addition, all scopes created within a native method 1512must be closed before returning from that method. 1513 1514Taking the earlier example, adding calls to [`napi_open_handle_scope`][] and 1515[`napi_close_handle_scope`][] would ensure that at most a single handle 1516is valid throughout the execution of the loop: 1517 1518```c 1519for (int i = 0; i < 1000000; i++) { 1520 napi_handle_scope scope; 1521 napi_status status = napi_open_handle_scope(env, &scope); 1522 if (status != napi_ok) { 1523 break; 1524 } 1525 napi_value result; 1526 status = napi_get_element(env, object, i, &result); 1527 if (status != napi_ok) { 1528 break; 1529 } 1530 // do something with element 1531 status = napi_close_handle_scope(env, scope); 1532 if (status != napi_ok) { 1533 break; 1534 } 1535} 1536``` 1537 1538When nesting scopes, there are cases where a handle from an 1539inner scope needs to live beyond the lifespan of that scope. Node-API supports 1540an 'escapable scope' in order to support this case. An escapable scope 1541allows one handle to be 'promoted' so that it 'escapes' the 1542current scope and the lifespan of the handle changes from the current 1543scope to that of the outer scope. 1544 1545The methods available to open/close escapable scopes are 1546[`napi_open_escapable_handle_scope`][] and 1547[`napi_close_escapable_handle_scope`][]. 1548 1549The request to promote a handle is made through [`napi_escape_handle`][] which 1550can only be called once. 1551 1552#### `napi_open_handle_scope` 1553 1554<!-- YAML 1555added: v8.0.0 1556napiVersion: 1 1557--> 1558 1559```c 1560NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, 1561 napi_handle_scope* result); 1562``` 1563 1564* `[in] env`: The environment that the API is invoked under. 1565* `[out] result`: `napi_value` representing the new scope. 1566 1567Returns `napi_ok` if the API succeeded. 1568 1569This API opens a new scope. 1570 1571#### `napi_close_handle_scope` 1572 1573<!-- YAML 1574added: v8.0.0 1575napiVersion: 1 1576--> 1577 1578```c 1579NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, 1580 napi_handle_scope scope); 1581``` 1582 1583* `[in] env`: The environment that the API is invoked under. 1584* `[in] scope`: `napi_value` representing the scope to be closed. 1585 1586Returns `napi_ok` if the API succeeded. 1587 1588This API closes the scope passed in. Scopes must be closed in the 1589reverse order from which they were created. 1590 1591This API can be called even if there is a pending JavaScript exception. 1592 1593#### `napi_open_escapable_handle_scope` 1594 1595<!-- YAML 1596added: v8.0.0 1597napiVersion: 1 1598--> 1599 1600```c 1601NAPI_EXTERN napi_status 1602 napi_open_escapable_handle_scope(napi_env env, 1603 napi_handle_scope* result); 1604``` 1605 1606* `[in] env`: The environment that the API is invoked under. 1607* `[out] result`: `napi_value` representing the new scope. 1608 1609Returns `napi_ok` if the API succeeded. 1610 1611This API opens a new scope from which one object can be promoted 1612to the outer scope. 1613 1614#### `napi_close_escapable_handle_scope` 1615 1616<!-- YAML 1617added: v8.0.0 1618napiVersion: 1 1619--> 1620 1621```c 1622NAPI_EXTERN napi_status 1623 napi_close_escapable_handle_scope(napi_env env, 1624 napi_handle_scope scope); 1625``` 1626 1627* `[in] env`: The environment that the API is invoked under. 1628* `[in] scope`: `napi_value` representing the scope to be closed. 1629 1630Returns `napi_ok` if the API succeeded. 1631 1632This API closes the scope passed in. Scopes must be closed in the 1633reverse order from which they were created. 1634 1635This API can be called even if there is a pending JavaScript exception. 1636 1637#### `napi_escape_handle` 1638 1639<!-- YAML 1640added: v8.0.0 1641napiVersion: 1 1642--> 1643 1644```c 1645napi_status napi_escape_handle(napi_env env, 1646 napi_escapable_handle_scope scope, 1647 napi_value escapee, 1648 napi_value* result); 1649``` 1650 1651* `[in] env`: The environment that the API is invoked under. 1652* `[in] scope`: `napi_value` representing the current scope. 1653* `[in] escapee`: `napi_value` representing the JavaScript `Object` to be 1654 escaped. 1655* `[out] result`: `napi_value` representing the handle to the escaped `Object` 1656 in the outer scope. 1657 1658Returns `napi_ok` if the API succeeded. 1659 1660This API promotes the handle to the JavaScript object so that it is valid 1661for the lifetime of the outer scope. It can only be called once per scope. 1662If it is called more than once an error will be returned. 1663 1664This API can be called even if there is a pending JavaScript exception. 1665 1666### References to values with a lifespan longer than that of the native method 1667 1668In some cases, an addon will need to be able to create and reference values 1669with a lifespan longer than that of a single native method invocation. For 1670example, to create a constructor and later use that constructor 1671in a request to create instances, it must be possible to reference 1672the constructor object across many different instance creation requests. This 1673would not be possible with a normal handle returned as a `napi_value` as 1674described in the earlier section. The lifespan of a normal handle is 1675managed by scopes and all scopes must be closed before the end of a native 1676method. 1677 1678Node-API provides methods for creating persistent references to values. 1679Currently Node-API only allows references to be created for a 1680limited set of value types, including object, external, function, and symbol. 1681 1682Each reference has an associated count with a value of 0 or higher, 1683which determines whether the reference will keep the corresponding value alive. 1684References with a count of 0 do not prevent values from being collected. 1685Values of object (object, function, external) and symbol types are becoming 1686'weak' references and can still be accessed while they are not collected. 1687Any count greater than 0 will prevent the values from being collected. 1688 1689Symbol values have different flavors. The true weak reference behavior is 1690only supported by local symbols created with the `napi_create_symbol` function 1691or the JavaScript `Symbol()` constructor calls. Globally registered symbols 1692created with the `node_api_symbol_for` function or JavaScript `Symbol.for()` 1693function calls remain always strong references because the garbage collector 1694does not collect them. The same is true for well-known symbols such as 1695`Symbol.iterator`. They are also never collected by the garbage collector. 1696 1697References can be created with an initial reference count. The count can 1698then be modified through [`napi_reference_ref`][] and 1699[`napi_reference_unref`][]. If an object is collected while the count 1700for a reference is 0, all subsequent calls to 1701get the object associated with the reference [`napi_get_reference_value`][] 1702will return `NULL` for the returned `napi_value`. An attempt to call 1703[`napi_reference_ref`][] for a reference whose object has been collected 1704results in an error. 1705 1706References must be deleted once they are no longer required by the addon. When 1707a reference is deleted, it will no longer prevent the corresponding object from 1708being collected. Failure to delete a persistent reference results in 1709a 'memory leak' with both the native memory for the persistent reference and 1710the corresponding object on the heap being retained forever. 1711 1712There can be multiple persistent references created which refer to the same 1713object, each of which will either keep the object live or not based on its 1714individual count. Multiple persistent references to the same object 1715can result in unexpectedly keeping alive native memory. The native structures 1716for a persistent reference must be kept alive until finalizers for the 1717referenced object are executed. If a new persistent reference is created 1718for the same object, the finalizers for that object will not be 1719run and the native memory pointed by the earlier persistent reference 1720will not be freed. This can be avoided by calling 1721`napi_delete_reference` in addition to `napi_reference_unref` when possible. 1722 1723**Change History:** 1724 1725* Experimental (`NAPI_EXPERIMENTAL` is defined): 1726 1727 References can be created for all value types. The new supported value 1728 types do not support weak reference semantic and the values of these types 1729 are released when the reference count becomes 0 and cannot be accessed from 1730 the reference anymore. 1731 1732#### `napi_create_reference` 1733 1734<!-- YAML 1735added: v8.0.0 1736napiVersion: 1 1737--> 1738 1739```c 1740NAPI_EXTERN napi_status napi_create_reference(napi_env env, 1741 napi_value value, 1742 uint32_t initial_refcount, 1743 napi_ref* result); 1744``` 1745 1746* `[in] env`: The environment that the API is invoked under. 1747* `[in] value`: The `napi_value` for which a reference is being created. 1748* `[in] initial_refcount`: Initial reference count for the new reference. 1749* `[out] result`: `napi_ref` pointing to the new reference. 1750 1751Returns `napi_ok` if the API succeeded. 1752 1753This API creates a new reference with the specified reference count 1754to the value passed in. 1755 1756#### `napi_delete_reference` 1757 1758<!-- YAML 1759added: v8.0.0 1760napiVersion: 1 1761--> 1762 1763```c 1764NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref); 1765``` 1766 1767* `[in] env`: The environment that the API is invoked under. 1768* `[in] ref`: `napi_ref` to be deleted. 1769 1770Returns `napi_ok` if the API succeeded. 1771 1772This API deletes the reference passed in. 1773 1774This API can be called even if there is a pending JavaScript exception. 1775 1776#### `napi_reference_ref` 1777 1778<!-- YAML 1779added: v8.0.0 1780napiVersion: 1 1781--> 1782 1783```c 1784NAPI_EXTERN napi_status napi_reference_ref(napi_env env, 1785 napi_ref ref, 1786 uint32_t* result); 1787``` 1788 1789* `[in] env`: The environment that the API is invoked under. 1790* `[in] ref`: `napi_ref` for which the reference count will be incremented. 1791* `[out] result`: The new reference count. 1792 1793Returns `napi_ok` if the API succeeded. 1794 1795This API increments the reference count for the reference 1796passed in and returns the resulting reference count. 1797 1798#### `napi_reference_unref` 1799 1800<!-- YAML 1801added: v8.0.0 1802napiVersion: 1 1803--> 1804 1805```c 1806NAPI_EXTERN napi_status napi_reference_unref(napi_env env, 1807 napi_ref ref, 1808 uint32_t* result); 1809``` 1810 1811* `[in] env`: The environment that the API is invoked under. 1812* `[in] ref`: `napi_ref` for which the reference count will be decremented. 1813* `[out] result`: The new reference count. 1814 1815Returns `napi_ok` if the API succeeded. 1816 1817This API decrements the reference count for the reference 1818passed in and returns the resulting reference count. 1819 1820#### `napi_get_reference_value` 1821 1822<!-- YAML 1823added: v8.0.0 1824napiVersion: 1 1825--> 1826 1827```c 1828NAPI_EXTERN napi_status napi_get_reference_value(napi_env env, 1829 napi_ref ref, 1830 napi_value* result); 1831``` 1832 1833* `[in] env`: The environment that the API is invoked under. 1834* `[in] ref`: The `napi_ref` for which the corresponding value is 1835 being requested. 1836* `[out] result`: The `napi_value` referenced by the `napi_ref`. 1837 1838Returns `napi_ok` if the API succeeded. 1839 1840If still valid, this API returns the `napi_value` representing the 1841JavaScript value associated with the `napi_ref`. Otherwise, result 1842will be `NULL`. 1843 1844### Cleanup on exit of the current Node.js environment 1845 1846While a Node.js process typically releases all its resources when exiting, 1847embedders of Node.js, or future Worker support, may require addons to register 1848clean-up hooks that will be run once the current Node.js environment exits. 1849 1850Node-API provides functions for registering and un-registering such callbacks. 1851When those callbacks are run, all resources that are being held by the addon 1852should be freed up. 1853 1854#### `napi_add_env_cleanup_hook` 1855 1856<!-- YAML 1857added: v10.2.0 1858napiVersion: 3 1859--> 1860 1861```c 1862NODE_EXTERN napi_status napi_add_env_cleanup_hook(node_api_nogc_env env, 1863 napi_cleanup_hook fun, 1864 void* arg); 1865``` 1866 1867Registers `fun` as a function to be run with the `arg` parameter once the 1868current Node.js environment exits. 1869 1870A function can safely be specified multiple times with different 1871`arg` values. In that case, it will be called multiple times as well. 1872Providing the same `fun` and `arg` values multiple times is not allowed 1873and will lead the process to abort. 1874 1875The hooks will be called in reverse order, i.e. the most recently added one 1876will be called first. 1877 1878Removing this hook can be done by using [`napi_remove_env_cleanup_hook`][]. 1879Typically, that happens when the resource for which this hook was added 1880is being torn down anyway. 1881 1882For asynchronous cleanup, [`napi_add_async_cleanup_hook`][] is available. 1883 1884#### `napi_remove_env_cleanup_hook` 1885 1886<!-- YAML 1887added: v10.2.0 1888napiVersion: 3 1889--> 1890 1891```c 1892NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(node_api_nogc_env env, 1893 void (*fun)(void* arg), 1894 void* arg); 1895``` 1896 1897Unregisters `fun` as a function to be run with the `arg` parameter once the 1898current Node.js environment exits. Both the argument and the function value 1899need to be exact matches. 1900 1901The function must have originally been registered 1902with `napi_add_env_cleanup_hook`, otherwise the process will abort. 1903 1904#### `napi_add_async_cleanup_hook` 1905 1906<!-- YAML 1907added: 1908 - v14.8.0 1909 - v12.19.0 1910napiVersion: 8 1911changes: 1912 - version: 1913 - v14.10.0 1914 - v12.19.0 1915 pr-url: https://github.com/nodejs/node/pull/34819 1916 description: Changed signature of the `hook` callback. 1917--> 1918 1919```c 1920NAPI_EXTERN napi_status napi_add_async_cleanup_hook( 1921 node_api_nogc_env env, 1922 napi_async_cleanup_hook hook, 1923 void* arg, 1924 napi_async_cleanup_hook_handle* remove_handle); 1925``` 1926 1927* `[in] env`: The environment that the API is invoked under. 1928* `[in] hook`: The function pointer to call at environment teardown. 1929* `[in] arg`: The pointer to pass to `hook` when it gets called. 1930* `[out] remove_handle`: Optional handle that refers to the asynchronous cleanup 1931 hook. 1932 1933Registers `hook`, which is a function of type [`napi_async_cleanup_hook`][], as 1934a function to be run with the `remove_handle` and `arg` parameters once the 1935current Node.js environment exits. 1936 1937Unlike [`napi_add_env_cleanup_hook`][], the hook is allowed to be asynchronous. 1938 1939Otherwise, behavior generally matches that of [`napi_add_env_cleanup_hook`][]. 1940 1941If `remove_handle` is not `NULL`, an opaque value will be stored in it 1942that must later be passed to [`napi_remove_async_cleanup_hook`][], 1943regardless of whether the hook has already been invoked. 1944Typically, that happens when the resource for which this hook was added 1945is being torn down anyway. 1946 1947#### `napi_remove_async_cleanup_hook` 1948 1949<!-- YAML 1950added: 1951 - v14.8.0 1952 - v12.19.0 1953changes: 1954 - version: 1955 - v14.10.0 1956 - v12.19.0 1957 pr-url: https://github.com/nodejs/node/pull/34819 1958 description: Removed `env` parameter. 1959--> 1960 1961```c 1962NAPI_EXTERN napi_status napi_remove_async_cleanup_hook( 1963 napi_async_cleanup_hook_handle remove_handle); 1964``` 1965 1966* `[in] remove_handle`: The handle to an asynchronous cleanup hook that was 1967 created with [`napi_add_async_cleanup_hook`][]. 1968 1969Unregisters the cleanup hook corresponding to `remove_handle`. This will prevent 1970the hook from being executed, unless it has already started executing. 1971This must be called on any `napi_async_cleanup_hook_handle` value obtained 1972from [`napi_add_async_cleanup_hook`][]. 1973 1974### Finalization on the exit of the Node.js environment 1975 1976The Node.js environment may be torn down at an arbitrary time as soon as 1977possible with JavaScript execution disallowed, like on the request of 1978[`worker.terminate()`][]. When the environment is being torn down, the 1979registered `napi_finalize` callbacks of JavaScript objects, thread-safe 1980functions and environment instance data are invoked immediately and 1981independently. 1982 1983The invocation of `napi_finalize` callbacks is scheduled after the manually 1984registered cleanup hooks. In order to ensure a proper order of addon 1985finalization during environment shutdown to avoid use-after-free in the 1986`napi_finalize` callback, addons should register a cleanup hook with 1987`napi_add_env_cleanup_hook` and `napi_add_async_cleanup_hook` to manually 1988release the allocated resource in a proper order. 1989 1990## Module registration 1991 1992Node-API modules are registered in a manner similar to other modules 1993except that instead of using the `NODE_MODULE` macro the following 1994is used: 1995 1996```c 1997NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) 1998``` 1999 2000The next difference is the signature for the `Init` method. For a Node-API 2001module it is as follows: 2002 2003```c 2004napi_value Init(napi_env env, napi_value exports); 2005``` 2006 2007The return value from `Init` is treated as the `exports` object for the module. 2008The `Init` method is passed an empty object via the `exports` parameter as a 2009convenience. If `Init` returns `NULL`, the parameter passed as `exports` is 2010exported by the module. Node-API modules cannot modify the `module` object but 2011can specify anything as the `exports` property of the module. 2012 2013To add the method `hello` as a function so that it can be called as a method 2014provided by the addon: 2015 2016```c 2017napi_value Init(napi_env env, napi_value exports) { 2018 napi_status status; 2019 napi_property_descriptor desc = { 2020 "hello", 2021 NULL, 2022 Method, 2023 NULL, 2024 NULL, 2025 NULL, 2026 napi_writable | napi_enumerable | napi_configurable, 2027 NULL 2028 }; 2029 status = napi_define_properties(env, exports, 1, &desc); 2030 if (status != napi_ok) return NULL; 2031 return exports; 2032} 2033``` 2034 2035To set a function to be returned by the `require()` for the addon: 2036 2037```c 2038napi_value Init(napi_env env, napi_value exports) { 2039 napi_value method; 2040 napi_status status; 2041 status = napi_create_function(env, "exports", NAPI_AUTO_LENGTH, Method, NULL, &method); 2042 if (status != napi_ok) return NULL; 2043 return method; 2044} 2045``` 2046 2047To define a class so that new instances can be created (often used with 2048[Object wrap][]): 2049 2050```c 2051// NOTE: partial example, not all referenced code is included 2052napi_value Init(napi_env env, napi_value exports) { 2053 napi_status status; 2054 napi_property_descriptor properties[] = { 2055 { "value", NULL, NULL, GetValue, SetValue, NULL, napi_writable | napi_configurable, NULL }, 2056 DECLARE_NAPI_METHOD("plusOne", PlusOne), 2057 DECLARE_NAPI_METHOD("multiply", Multiply), 2058 }; 2059 2060 napi_value cons; 2061 status = 2062 napi_define_class(env, "MyObject", New, NULL, 3, properties, &cons); 2063 if (status != napi_ok) return NULL; 2064 2065 status = napi_create_reference(env, cons, 1, &constructor); 2066 if (status != napi_ok) return NULL; 2067 2068 status = napi_set_named_property(env, exports, "MyObject", cons); 2069 if (status != napi_ok) return NULL; 2070 2071 return exports; 2072} 2073``` 2074 2075You can also use the `NAPI_MODULE_INIT` macro, which acts as a shorthand 2076for `NAPI_MODULE` and defining an `Init` function: 2077 2078```c 2079NAPI_MODULE_INIT(/* napi_env env, napi_value exports */) { 2080 napi_value answer; 2081 napi_status result; 2082 2083 status = napi_create_int64(env, 42, &answer); 2084 if (status != napi_ok) return NULL; 2085 2086 status = napi_set_named_property(env, exports, "answer", answer); 2087 if (status != napi_ok) return NULL; 2088 2089 return exports; 2090} 2091``` 2092 2093The parameters `env` and `exports` are provided to the body of the 2094`NAPI_MODULE_INIT` macro. 2095 2096All Node-API addons are context-aware, meaning they may be loaded multiple 2097times. There are a few design considerations when declaring such a module. 2098The documentation on [context-aware addons][] provides more details. 2099 2100The variables `env` and `exports` will be available inside the function body 2101following the macro invocation. 2102 2103For more details on setting properties on objects, see the section on 2104[Working with JavaScript properties][]. 2105 2106For more details on building addon modules in general, refer to the existing 2107API. 2108 2109## Working with JavaScript values 2110 2111Node-API exposes a set of APIs to create all types of JavaScript values. 2112Some of these types are documented under [Section 6][] 2113of the [ECMAScript Language Specification][]. 2114 2115Fundamentally, these APIs are used to do one of the following: 2116 21171. Create a new JavaScript object 21182. Convert from a primitive C type to a Node-API value 21193. Convert from Node-API value to a primitive C type 21204. Get global instances including `undefined` and `null` 2121 2122Node-API values are represented by the type `napi_value`. 2123Any Node-API call that requires a JavaScript value takes in a `napi_value`. 2124In some cases, the API does check the type of the `napi_value` up-front. 2125However, for better performance, it's better for the caller to make sure that 2126the `napi_value` in question is of the JavaScript type expected by the API. 2127 2128### Enum types 2129 2130#### `napi_key_collection_mode` 2131 2132<!-- YAML 2133added: 2134 - v13.7.0 2135 - v12.17.0 2136 - v10.20.0 2137napiVersion: 6 2138--> 2139 2140```c 2141typedef enum { 2142 napi_key_include_prototypes, 2143 napi_key_own_only 2144} napi_key_collection_mode; 2145``` 2146 2147Describes the `Keys/Properties` filter enums: 2148 2149`napi_key_collection_mode` limits the range of collected properties. 2150 2151`napi_key_own_only` limits the collected properties to the given 2152object only. `napi_key_include_prototypes` will include all keys 2153of the objects's prototype chain as well. 2154 2155#### `napi_key_filter` 2156 2157<!-- YAML 2158added: 2159 - v13.7.0 2160 - v12.17.0 2161 - v10.20.0 2162napiVersion: 6 2163--> 2164 2165```c 2166typedef enum { 2167 napi_key_all_properties = 0, 2168 napi_key_writable = 1, 2169 napi_key_enumerable = 1 << 1, 2170 napi_key_configurable = 1 << 2, 2171 napi_key_skip_strings = 1 << 3, 2172 napi_key_skip_symbols = 1 << 4 2173} napi_key_filter; 2174``` 2175 2176Property filter bits. They can be or'ed to build a composite filter. 2177 2178#### `napi_key_conversion` 2179 2180<!-- YAML 2181added: 2182 - v13.7.0 2183 - v12.17.0 2184 - v10.20.0 2185napiVersion: 6 2186--> 2187 2188```c 2189typedef enum { 2190 napi_key_keep_numbers, 2191 napi_key_numbers_to_strings 2192} napi_key_conversion; 2193``` 2194 2195`napi_key_numbers_to_strings` will convert integer indices to 2196strings. `napi_key_keep_numbers` will return numbers for integer 2197indices. 2198 2199#### `napi_valuetype` 2200 2201```c 2202typedef enum { 2203 // ES6 types (corresponds to typeof) 2204 napi_undefined, 2205 napi_null, 2206 napi_boolean, 2207 napi_number, 2208 napi_string, 2209 napi_symbol, 2210 napi_object, 2211 napi_function, 2212 napi_external, 2213 napi_bigint, 2214} napi_valuetype; 2215``` 2216 2217Describes the type of a `napi_value`. This generally corresponds to the types 2218described in [Section 6.1][] of the ECMAScript Language Specification. 2219In addition to types in that section, `napi_valuetype` can also represent 2220`Function`s and `Object`s with external data. 2221 2222A JavaScript value of type `napi_external` appears in JavaScript as a plain 2223object such that no properties can be set on it, and no prototype. 2224 2225#### `napi_typedarray_type` 2226 2227```c 2228typedef enum { 2229 napi_int8_array, 2230 napi_uint8_array, 2231 napi_uint8_clamped_array, 2232 napi_int16_array, 2233 napi_uint16_array, 2234 napi_int32_array, 2235 napi_uint32_array, 2236 napi_float32_array, 2237 napi_float64_array, 2238 napi_bigint64_array, 2239 napi_biguint64_array, 2240} napi_typedarray_type; 2241``` 2242 2243This represents the underlying binary scalar datatype of the `TypedArray`. 2244Elements of this enum correspond to 2245[Section 22.2][] of the [ECMAScript Language Specification][]. 2246 2247### Object creation functions 2248 2249#### `napi_create_array` 2250 2251<!-- YAML 2252added: v8.0.0 2253napiVersion: 1 2254--> 2255 2256```c 2257napi_status napi_create_array(napi_env env, napi_value* result) 2258``` 2259 2260* `[in] env`: The environment that the Node-API call is invoked under. 2261* `[out] result`: A `napi_value` representing a JavaScript `Array`. 2262 2263Returns `napi_ok` if the API succeeded. 2264 2265This API returns a Node-API value corresponding to a JavaScript `Array` type. 2266JavaScript arrays are described in 2267[Section 22.1][] of the ECMAScript Language Specification. 2268 2269#### `napi_create_array_with_length` 2270 2271<!-- YAML 2272added: v8.0.0 2273napiVersion: 1 2274--> 2275 2276```c 2277napi_status napi_create_array_with_length(napi_env env, 2278 size_t length, 2279 napi_value* result) 2280``` 2281 2282* `[in] env`: The environment that the API is invoked under. 2283* `[in] length`: The initial length of the `Array`. 2284* `[out] result`: A `napi_value` representing a JavaScript `Array`. 2285 2286Returns `napi_ok` if the API succeeded. 2287 2288This API returns a Node-API value corresponding to a JavaScript `Array` type. 2289The `Array`'s length property is set to the passed-in length parameter. 2290However, the underlying buffer is not guaranteed to be pre-allocated by the VM 2291when the array is created. That behavior is left to the underlying VM 2292implementation. If the buffer must be a contiguous block of memory that can be 2293directly read and/or written via C, consider using 2294[`napi_create_external_arraybuffer`][]. 2295 2296JavaScript arrays are described in 2297[Section 22.1][] of the ECMAScript Language Specification. 2298 2299#### `napi_create_arraybuffer` 2300 2301<!-- YAML 2302added: v8.0.0 2303napiVersion: 1 2304--> 2305 2306```c 2307napi_status napi_create_arraybuffer(napi_env env, 2308 size_t byte_length, 2309 void** data, 2310 napi_value* result) 2311``` 2312 2313* `[in] env`: The environment that the API is invoked under. 2314* `[in] length`: The length in bytes of the array buffer to create. 2315* `[out] data`: Pointer to the underlying byte buffer of the `ArrayBuffer`. 2316 `data` can optionally be ignored by passing `NULL`. 2317* `[out] result`: A `napi_value` representing a JavaScript `ArrayBuffer`. 2318 2319Returns `napi_ok` if the API succeeded. 2320 2321This API returns a Node-API value corresponding to a JavaScript `ArrayBuffer`. 2322`ArrayBuffer`s are used to represent fixed-length binary data buffers. They are 2323normally used as a backing-buffer for `TypedArray` objects. 2324The `ArrayBuffer` allocated will have an underlying byte buffer whose size is 2325determined by the `length` parameter that's passed in. 2326The underlying buffer is optionally returned back to the caller in case the 2327caller wants to directly manipulate the buffer. This buffer can only be 2328written to directly from native code. To write to this buffer from JavaScript, 2329a typed array or `DataView` object would need to be created. 2330 2331JavaScript `ArrayBuffer` objects are described in 2332[Section 24.1][] of the ECMAScript Language Specification. 2333 2334#### `napi_create_buffer` 2335 2336<!-- YAML 2337added: v8.0.0 2338napiVersion: 1 2339--> 2340 2341```c 2342napi_status napi_create_buffer(napi_env env, 2343 size_t size, 2344 void** data, 2345 napi_value* result) 2346``` 2347 2348* `[in] env`: The environment that the API is invoked under. 2349* `[in] size`: Size in bytes of the underlying buffer. 2350* `[out] data`: Raw pointer to the underlying buffer. 2351 `data` can optionally be ignored by passing `NULL`. 2352* `[out] result`: A `napi_value` representing a `node::Buffer`. 2353 2354Returns `napi_ok` if the API succeeded. 2355 2356This API allocates a `node::Buffer` object. While this is still a 2357fully-supported data structure, in most cases using a `TypedArray` will suffice. 2358 2359#### `napi_create_buffer_copy` 2360 2361<!-- YAML 2362added: v8.0.0 2363napiVersion: 1 2364--> 2365 2366```c 2367napi_status napi_create_buffer_copy(napi_env env, 2368 size_t length, 2369 const void* data, 2370 void** result_data, 2371 napi_value* result) 2372``` 2373 2374* `[in] env`: The environment that the API is invoked under. 2375* `[in] size`: Size in bytes of the input buffer (should be the same as the size 2376 of the new buffer). 2377* `[in] data`: Raw pointer to the underlying buffer to copy from. 2378* `[out] result_data`: Pointer to the new `Buffer`'s underlying data buffer. 2379 `result_data` can optionally be ignored by passing `NULL`. 2380* `[out] result`: A `napi_value` representing a `node::Buffer`. 2381 2382Returns `napi_ok` if the API succeeded. 2383 2384This API allocates a `node::Buffer` object and initializes it with data copied 2385from the passed-in buffer. While this is still a fully-supported data 2386structure, in most cases using a `TypedArray` will suffice. 2387 2388#### `napi_create_date` 2389 2390<!-- YAML 2391added: 2392 - v11.11.0 2393 - v10.17.0 2394napiVersion: 5 2395--> 2396 2397```c 2398napi_status napi_create_date(napi_env env, 2399 double time, 2400 napi_value* result); 2401``` 2402 2403* `[in] env`: The environment that the API is invoked under. 2404* `[in] time`: ECMAScript time value in milliseconds since 01 January, 1970 UTC. 2405* `[out] result`: A `napi_value` representing a JavaScript `Date`. 2406 2407Returns `napi_ok` if the API succeeded. 2408 2409This API does not observe leap seconds; they are ignored, as 2410ECMAScript aligns with POSIX time specification. 2411 2412This API allocates a JavaScript `Date` object. 2413 2414JavaScript `Date` objects are described in 2415[Section 20.3][] of the ECMAScript Language Specification. 2416 2417#### `napi_create_external` 2418 2419<!-- YAML 2420added: v8.0.0 2421napiVersion: 1 2422--> 2423 2424```c 2425napi_status napi_create_external(napi_env env, 2426 void* data, 2427 napi_finalize finalize_cb, 2428 void* finalize_hint, 2429 napi_value* result) 2430``` 2431 2432* `[in] env`: The environment that the API is invoked under. 2433* `[in] data`: Raw pointer to the external data. 2434* `[in] finalize_cb`: Optional callback to call when the external value is being 2435 collected. [`napi_finalize`][] provides more details. 2436* `[in] finalize_hint`: Optional hint to pass to the finalize callback during 2437 collection. 2438* `[out] result`: A `napi_value` representing an external value. 2439 2440Returns `napi_ok` if the API succeeded. 2441 2442This API allocates a JavaScript value with external data attached to it. This 2443is used to pass external data through JavaScript code, so it can be retrieved 2444later by native code using [`napi_get_value_external`][]. 2445 2446The API adds a `napi_finalize` callback which will be called when the JavaScript 2447object just created has been garbage collected. 2448 2449The created value is not an object, and therefore does not support additional 2450properties. It is considered a distinct value type: calling `napi_typeof()` with 2451an external value yields `napi_external`. 2452 2453#### `napi_create_external_arraybuffer` 2454 2455<!-- YAML 2456added: v8.0.0 2457napiVersion: 1 2458--> 2459 2460```c 2461napi_status 2462napi_create_external_arraybuffer(napi_env env, 2463 void* external_data, 2464 size_t byte_length, 2465 napi_finalize finalize_cb, 2466 void* finalize_hint, 2467 napi_value* result) 2468``` 2469 2470* `[in] env`: The environment that the API is invoked under. 2471* `[in] external_data`: Pointer to the underlying byte buffer of the 2472 `ArrayBuffer`. 2473* `[in] byte_length`: The length in bytes of the underlying buffer. 2474* `[in] finalize_cb`: Optional callback to call when the `ArrayBuffer` is being 2475 collected. [`napi_finalize`][] provides more details. 2476* `[in] finalize_hint`: Optional hint to pass to the finalize callback during 2477 collection. 2478* `[out] result`: A `napi_value` representing a JavaScript `ArrayBuffer`. 2479 2480Returns `napi_ok` if the API succeeded. 2481 2482**Some runtimes other than Node.js have dropped support for external buffers**. 2483On runtimes other than Node.js this method may return 2484`napi_no_external_buffers_allowed` to indicate that external 2485buffers are not supported. One such runtime is Electron as 2486described in this issue 2487[electron/issues/35801](https://github.com/electron/electron/issues/35801). 2488 2489In order to maintain broadest compatibility with all runtimes 2490you may define `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` in your addon before 2491includes for the node-api headers. Doing so will hide the 2 functions 2492that create external buffers. This will ensure a compilation error 2493occurs if you accidentally use one of these methods. 2494 2495This API returns a Node-API value corresponding to a JavaScript `ArrayBuffer`. 2496The underlying byte buffer of the `ArrayBuffer` is externally allocated and 2497managed. The caller must ensure that the byte buffer remains valid until the 2498finalize callback is called. 2499 2500The API adds a `napi_finalize` callback which will be called when the JavaScript 2501object just created has been garbage collected. 2502 2503JavaScript `ArrayBuffer`s are described in 2504[Section 24.1][] of the ECMAScript Language Specification. 2505 2506#### `napi_create_external_buffer` 2507 2508<!-- YAML 2509added: v8.0.0 2510napiVersion: 1 2511--> 2512 2513```c 2514napi_status napi_create_external_buffer(napi_env env, 2515 size_t length, 2516 void* data, 2517 napi_finalize finalize_cb, 2518 void* finalize_hint, 2519 napi_value* result) 2520``` 2521 2522* `[in] env`: The environment that the API is invoked under. 2523* `[in] length`: Size in bytes of the input buffer (should be the same as the 2524 size of the new buffer). 2525* `[in] data`: Raw pointer to the underlying buffer to expose to JavaScript. 2526* `[in] finalize_cb`: Optional callback to call when the `ArrayBuffer` is being 2527 collected. [`napi_finalize`][] provides more details. 2528* `[in] finalize_hint`: Optional hint to pass to the finalize callback during 2529 collection. 2530* `[out] result`: A `napi_value` representing a `node::Buffer`. 2531 2532Returns `napi_ok` if the API succeeded. 2533 2534**Some runtimes other than Node.js have dropped support for external buffers**. 2535On runtimes other than Node.js this method may return 2536`napi_no_external_buffers_allowed` to indicate that external 2537buffers are not supported. One such runtime is Electron as 2538described in this issue 2539[electron/issues/35801](https://github.com/electron/electron/issues/35801). 2540 2541In order to maintain broadest compatibility with all runtimes 2542you may define `NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED` in your addon before 2543includes for the node-api headers. Doing so will hide the 2 functions 2544that create external buffers. This will ensure a compilation error 2545occurs if you accidentally use one of these methods. 2546 2547This API allocates a `node::Buffer` object and initializes it with data 2548backed by the passed in buffer. While this is still a fully-supported data 2549structure, in most cases using a `TypedArray` will suffice. 2550 2551The API adds a `napi_finalize` callback which will be called when the JavaScript 2552object just created has been garbage collected. 2553 2554For Node.js >=4 `Buffers` are `Uint8Array`s. 2555 2556#### `napi_create_object` 2557 2558<!-- YAML 2559added: v8.0.0 2560napiVersion: 1 2561--> 2562 2563```c 2564napi_status napi_create_object(napi_env env, napi_value* result) 2565``` 2566 2567* `[in] env`: The environment that the API is invoked under. 2568* `[out] result`: A `napi_value` representing a JavaScript `Object`. 2569 2570Returns `napi_ok` if the API succeeded. 2571 2572This API allocates a default JavaScript `Object`. 2573It is the equivalent of doing `new Object()` in JavaScript. 2574 2575The JavaScript `Object` type is described in [Section 6.1.7][] of the 2576ECMAScript Language Specification. 2577 2578#### `napi_create_symbol` 2579 2580<!-- YAML 2581added: v8.0.0 2582napiVersion: 1 2583--> 2584 2585```c 2586napi_status napi_create_symbol(napi_env env, 2587 napi_value description, 2588 napi_value* result) 2589``` 2590 2591* `[in] env`: The environment that the API is invoked under. 2592* `[in] description`: Optional `napi_value` which refers to a JavaScript 2593 `string` to be set as the description for the symbol. 2594* `[out] result`: A `napi_value` representing a JavaScript `symbol`. 2595 2596Returns `napi_ok` if the API succeeded. 2597 2598This API creates a JavaScript `symbol` value from a UTF8-encoded C string. 2599 2600The JavaScript `symbol` type is described in [Section 19.4][] 2601of the ECMAScript Language Specification. 2602 2603#### `node_api_symbol_for` 2604 2605<!-- YAML 2606added: v17.5.0 2607napiVersion: 9 2608--> 2609 2610```c 2611napi_status node_api_symbol_for(napi_env env, 2612 const char* utf8description, 2613 size_t length, 2614 napi_value* result) 2615``` 2616 2617* `[in] env`: The environment that the API is invoked under. 2618* `[in] utf8description`: UTF-8 C string representing the text to be used as the 2619 description for the symbol. 2620* `[in] length`: The length of the description string in bytes, or 2621 `NAPI_AUTO_LENGTH` if it is null-terminated. 2622* `[out] result`: A `napi_value` representing a JavaScript `symbol`. 2623 2624Returns `napi_ok` if the API succeeded. 2625 2626This API searches in the global registry for an existing symbol with the given 2627description. If the symbol already exists it will be returned, otherwise a new 2628symbol will be created in the registry. 2629 2630The JavaScript `symbol` type is described in [Section 19.4][] of the ECMAScript 2631Language Specification. 2632 2633#### `napi_create_typedarray` 2634 2635<!-- YAML 2636added: v8.0.0 2637napiVersion: 1 2638--> 2639 2640```c 2641napi_status napi_create_typedarray(napi_env env, 2642 napi_typedarray_type type, 2643 size_t length, 2644 napi_value arraybuffer, 2645 size_t byte_offset, 2646 napi_value* result) 2647``` 2648 2649* `[in] env`: The environment that the API is invoked under. 2650* `[in] type`: Scalar datatype of the elements within the `TypedArray`. 2651* `[in] length`: Number of elements in the `TypedArray`. 2652* `[in] arraybuffer`: `ArrayBuffer` underlying the typed array. 2653* `[in] byte_offset`: The byte offset within the `ArrayBuffer` from which to 2654 start projecting the `TypedArray`. 2655* `[out] result`: A `napi_value` representing a JavaScript `TypedArray`. 2656 2657Returns `napi_ok` if the API succeeded. 2658 2659This API creates a JavaScript `TypedArray` object over an existing 2660`ArrayBuffer`. `TypedArray` objects provide an array-like view over an 2661underlying data buffer where each element has the same underlying binary scalar 2662datatype. 2663 2664It's required that `(length * size_of_element) + byte_offset` should 2665be <= the size in bytes of the array passed in. If not, a `RangeError` exception 2666is raised. 2667 2668JavaScript `TypedArray` objects are described in 2669[Section 22.2][] of the ECMAScript Language Specification. 2670 2671#### `napi_create_dataview` 2672 2673<!-- YAML 2674added: v8.3.0 2675napiVersion: 1 2676--> 2677 2678```c 2679napi_status napi_create_dataview(napi_env env, 2680 size_t byte_length, 2681 napi_value arraybuffer, 2682 size_t byte_offset, 2683 napi_value* result) 2684``` 2685 2686* `[in] env`: The environment that the API is invoked under. 2687* `[in] length`: Number of elements in the `DataView`. 2688* `[in] arraybuffer`: `ArrayBuffer` underlying the `DataView`. 2689* `[in] byte_offset`: The byte offset within the `ArrayBuffer` from which to 2690 start projecting the `DataView`. 2691* `[out] result`: A `napi_value` representing a JavaScript `DataView`. 2692 2693Returns `napi_ok` if the API succeeded. 2694 2695This API creates a JavaScript `DataView` object over an existing `ArrayBuffer`. 2696`DataView` objects provide an array-like view over an underlying data buffer, 2697but one which allows items of different size and type in the `ArrayBuffer`. 2698 2699It is required that `byte_length + byte_offset` is less than or equal to the 2700size in bytes of the array passed in. If not, a `RangeError` exception is 2701raised. 2702 2703JavaScript `DataView` objects are described in 2704[Section 24.3][] of the ECMAScript Language Specification. 2705 2706### Functions to convert from C types to Node-API 2707 2708#### `napi_create_int32` 2709 2710<!-- YAML 2711added: v8.4.0 2712napiVersion: 1 2713--> 2714 2715```c 2716napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result) 2717``` 2718 2719* `[in] env`: The environment that the API is invoked under. 2720* `[in] value`: Integer value to be represented in JavaScript. 2721* `[out] result`: A `napi_value` representing a JavaScript `number`. 2722 2723Returns `napi_ok` if the API succeeded. 2724 2725This API is used to convert from the C `int32_t` type to the JavaScript 2726`number` type. 2727 2728The JavaScript `number` type is described in 2729[Section 6.1.6][] of the ECMAScript Language Specification. 2730 2731#### `napi_create_uint32` 2732 2733<!-- YAML 2734added: v8.4.0 2735napiVersion: 1 2736--> 2737 2738```c 2739napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result) 2740``` 2741 2742* `[in] env`: The environment that the API is invoked under. 2743* `[in] value`: Unsigned integer value to be represented in JavaScript. 2744* `[out] result`: A `napi_value` representing a JavaScript `number`. 2745 2746Returns `napi_ok` if the API succeeded. 2747 2748This API is used to convert from the C `uint32_t` type to the JavaScript 2749`number` type. 2750 2751The JavaScript `number` type is described in 2752[Section 6.1.6][] of the ECMAScript Language Specification. 2753 2754#### `napi_create_int64` 2755 2756<!-- YAML 2757added: v8.4.0 2758napiVersion: 1 2759--> 2760 2761```c 2762napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result) 2763``` 2764 2765* `[in] env`: The environment that the API is invoked under. 2766* `[in] value`: Integer value to be represented in JavaScript. 2767* `[out] result`: A `napi_value` representing a JavaScript `number`. 2768 2769Returns `napi_ok` if the API succeeded. 2770 2771This API is used to convert from the C `int64_t` type to the JavaScript 2772`number` type. 2773 2774The JavaScript `number` type is described in [Section 6.1.6][] 2775of the ECMAScript Language Specification. Note the complete range of `int64_t` 2776cannot be represented with full precision in JavaScript. Integer values 2777outside the range of [`Number.MIN_SAFE_INTEGER`][] `-(2**53 - 1)` - 2778[`Number.MAX_SAFE_INTEGER`][] `(2**53 - 1)` will lose precision. 2779 2780#### `napi_create_double` 2781 2782<!-- YAML 2783added: v8.4.0 2784napiVersion: 1 2785--> 2786 2787```c 2788napi_status napi_create_double(napi_env env, double value, napi_value* result) 2789``` 2790 2791* `[in] env`: The environment that the API is invoked under. 2792* `[in] value`: Double-precision value to be represented in JavaScript. 2793* `[out] result`: A `napi_value` representing a JavaScript `number`. 2794 2795Returns `napi_ok` if the API succeeded. 2796 2797This API is used to convert from the C `double` type to the JavaScript 2798`number` type. 2799 2800The JavaScript `number` type is described in 2801[Section 6.1.6][] of the ECMAScript Language Specification. 2802 2803#### `napi_create_bigint_int64` 2804 2805<!-- YAML 2806added: v10.7.0 2807napiVersion: 6 2808--> 2809 2810```c 2811napi_status napi_create_bigint_int64(napi_env env, 2812 int64_t value, 2813 napi_value* result); 2814``` 2815 2816* `[in] env`: The environment that the API is invoked under. 2817* `[in] value`: Integer value to be represented in JavaScript. 2818* `[out] result`: A `napi_value` representing a JavaScript `BigInt`. 2819 2820Returns `napi_ok` if the API succeeded. 2821 2822This API converts the C `int64_t` type to the JavaScript `BigInt` type. 2823 2824#### `napi_create_bigint_uint64` 2825 2826<!-- YAML 2827added: v10.7.0 2828napiVersion: 6 2829--> 2830 2831```c 2832napi_status napi_create_bigint_uint64(napi_env env, 2833 uint64_t value, 2834 napi_value* result); 2835``` 2836 2837* `[in] env`: The environment that the API is invoked under. 2838* `[in] value`: Unsigned integer value to be represented in JavaScript. 2839* `[out] result`: A `napi_value` representing a JavaScript `BigInt`. 2840 2841Returns `napi_ok` if the API succeeded. 2842 2843This API converts the C `uint64_t` type to the JavaScript `BigInt` type. 2844 2845#### `napi_create_bigint_words` 2846 2847<!-- YAML 2848added: v10.7.0 2849napiVersion: 6 2850--> 2851 2852```c 2853napi_status napi_create_bigint_words(napi_env env, 2854 int sign_bit, 2855 size_t word_count, 2856 const uint64_t* words, 2857 napi_value* result); 2858``` 2859 2860* `[in] env`: The environment that the API is invoked under. 2861* `[in] sign_bit`: Determines if the resulting `BigInt` will be positive or 2862 negative. 2863* `[in] word_count`: The length of the `words` array. 2864* `[in] words`: An array of `uint64_t` little-endian 64-bit words. 2865* `[out] result`: A `napi_value` representing a JavaScript `BigInt`. 2866 2867Returns `napi_ok` if the API succeeded. 2868 2869This API converts an array of unsigned 64-bit words into a single `BigInt` 2870value. 2871 2872The resulting `BigInt` is calculated as: (–1)<sup>`sign_bit`</sup> (`words[0]` 2873× (2<sup>64</sup>)<sup>0</sup> + `words[1]` × (2<sup>64</sup>)<sup>1</sup> + …) 2874 2875#### `napi_create_string_latin1` 2876 2877<!-- YAML 2878added: v8.0.0 2879napiVersion: 1 2880--> 2881 2882```c 2883napi_status napi_create_string_latin1(napi_env env, 2884 const char* str, 2885 size_t length, 2886 napi_value* result); 2887``` 2888 2889* `[in] env`: The environment that the API is invoked under. 2890* `[in] str`: Character buffer representing an ISO-8859-1-encoded string. 2891* `[in] length`: The length of the string in bytes, or `NAPI_AUTO_LENGTH` if it 2892 is null-terminated. 2893* `[out] result`: A `napi_value` representing a JavaScript `string`. 2894 2895Returns `napi_ok` if the API succeeded. 2896 2897This API creates a JavaScript `string` value from an ISO-8859-1-encoded C 2898string. The native string is copied. 2899 2900The JavaScript `string` type is described in 2901[Section 6.1.4][] of the ECMAScript Language Specification. 2902 2903#### `node_api_create_external_string_latin1` 2904 2905<!-- YAML 2906added: v18.18.0 2907--> 2908 2909> Stability: 1 - Experimental 2910 2911```c 2912napi_status 2913node_api_create_external_string_latin1(napi_env env, 2914 char* str, 2915 size_t length, 2916 napi_finalize finalize_callback, 2917 void* finalize_hint, 2918 napi_value* result, 2919 bool* copied); 2920``` 2921 2922* `[in] env`: The environment that the API is invoked under. 2923* `[in] str`: Character buffer representing an ISO-8859-1-encoded string. 2924* `[in] length`: The length of the string in bytes, or `NAPI_AUTO_LENGTH` if it 2925 is null-terminated. 2926* `[in] finalize_callback`: The function to call when the string is being 2927 collected. The function will be called with the following parameters: 2928 * `[in] env`: The environment in which the add-on is running. This value 2929 may be null if the string is being collected as part of the termination 2930 of the worker or the main Node.js instance. 2931 * `[in] data`: This is the value `str` as a `void*` pointer. 2932 * `[in] finalize_hint`: This is the value `finalize_hint` that was given 2933 to the API. 2934 [`napi_finalize`][] provides more details. 2935 This parameter is optional. Passing a null value means that the add-on 2936 doesn't need to be notified when the corresponding JavaScript string is 2937 collected. 2938* `[in] finalize_hint`: Optional hint to pass to the finalize callback during 2939 collection. 2940* `[out] result`: A `napi_value` representing a JavaScript `string`. 2941* `[out] copied`: Whether the string was copied. If it was, the finalizer will 2942 already have been invoked to destroy `str`. 2943 2944Returns `napi_ok` if the API succeeded. 2945 2946This API creates a JavaScript `string` value from an ISO-8859-1-encoded C 2947string. The native string may not be copied and must thus exist for the entire 2948life cycle of the JavaScript value. 2949 2950The JavaScript `string` type is described in 2951[Section 6.1.4][] of the ECMAScript Language Specification. 2952 2953#### `napi_create_string_utf16` 2954 2955<!-- YAML 2956added: v8.0.0 2957napiVersion: 1 2958--> 2959 2960```c 2961napi_status napi_create_string_utf16(napi_env env, 2962 const char16_t* str, 2963 size_t length, 2964 napi_value* result) 2965``` 2966 2967* `[in] env`: The environment that the API is invoked under. 2968* `[in] str`: Character buffer representing a UTF16-LE-encoded string. 2969* `[in] length`: The length of the string in two-byte code units, or 2970 `NAPI_AUTO_LENGTH` if it is null-terminated. 2971* `[out] result`: A `napi_value` representing a JavaScript `string`. 2972 2973Returns `napi_ok` if the API succeeded. 2974 2975This API creates a JavaScript `string` value from a UTF16-LE-encoded C string. 2976The native string is copied. 2977 2978The JavaScript `string` type is described in 2979[Section 6.1.4][] of the ECMAScript Language Specification. 2980 2981#### `node_api_create_external_string_utf16` 2982 2983<!-- YAML 2984added: v18.18.0 2985--> 2986 2987> Stability: 1 - Experimental 2988 2989```c 2990napi_status 2991node_api_create_external_string_utf16(napi_env env, 2992 char16_t* str, 2993 size_t length, 2994 napi_finalize finalize_callback, 2995 void* finalize_hint, 2996 napi_value* result, 2997 bool* copied); 2998``` 2999 3000* `[in] env`: The environment that the API is invoked under. 3001* `[in] str`: Character buffer representing a UTF16-LE-encoded string. 3002* `[in] length`: The length of the string in two-byte code units, or 3003 `NAPI_AUTO_LENGTH` if it is null-terminated. 3004* `[in] finalize_callback`: The function to call when the string is being 3005 collected. The function will be called with the following parameters: 3006 * `[in] env`: The environment in which the add-on is running. This value 3007 may be null if the string is being collected as part of the termination 3008 of the worker or the main Node.js instance. 3009 * `[in] data`: This is the value `str` as a `void*` pointer. 3010 * `[in] finalize_hint`: This is the value `finalize_hint` that was given 3011 to the API. 3012 [`napi_finalize`][] provides more details. 3013 This parameter is optional. Passing a null value means that the add-on 3014 doesn't need to be notified when the corresponding JavaScript string is 3015 collected. 3016* `[in] finalize_hint`: Optional hint to pass to the finalize callback during 3017 collection. 3018* `[out] result`: A `napi_value` representing a JavaScript `string`. 3019* `[out] copied`: Whether the string was copied. If it was, the finalizer will 3020 already have been invoked to destroy `str`. 3021 3022Returns `napi_ok` if the API succeeded. 3023 3024This API creates a JavaScript `string` value from a UTF16-LE-encoded C string. 3025The native string may not be copied and must thus exist for the entire life 3026cycle of the JavaScript value. 3027 3028The JavaScript `string` type is described in 3029[Section 6.1.4][] of the ECMAScript Language Specification. 3030 3031#### `napi_create_string_utf8` 3032 3033<!-- YAML 3034added: v8.0.0 3035napiVersion: 1 3036--> 3037 3038```c 3039napi_status napi_create_string_utf8(napi_env env, 3040 const char* str, 3041 size_t length, 3042 napi_value* result) 3043``` 3044 3045* `[in] env`: The environment that the API is invoked under. 3046* `[in] str`: Character buffer representing a UTF8-encoded string. 3047* `[in] length`: The length of the string in bytes, or `NAPI_AUTO_LENGTH` if it 3048 is null-terminated. 3049* `[out] result`: A `napi_value` representing a JavaScript `string`. 3050 3051Returns `napi_ok` if the API succeeded. 3052 3053This API creates a JavaScript `string` value from a UTF8-encoded C string. 3054The native string is copied. 3055 3056The JavaScript `string` type is described in 3057[Section 6.1.4][] of the ECMAScript Language Specification. 3058 3059### Functions to convert from Node-API to C types 3060 3061#### `napi_get_array_length` 3062 3063<!-- YAML 3064added: v8.0.0 3065napiVersion: 1 3066--> 3067 3068```c 3069napi_status napi_get_array_length(napi_env env, 3070 napi_value value, 3071 uint32_t* result) 3072``` 3073 3074* `[in] env`: The environment that the API is invoked under. 3075* `[in] value`: `napi_value` representing the JavaScript `Array` whose length is 3076 being queried. 3077* `[out] result`: `uint32` representing length of the array. 3078 3079Returns `napi_ok` if the API succeeded. 3080 3081This API returns the length of an array. 3082 3083`Array` length is described in [Section 22.1.4.1][] of the ECMAScript Language 3084Specification. 3085 3086#### `napi_get_arraybuffer_info` 3087 3088<!-- YAML 3089added: v8.0.0 3090napiVersion: 1 3091--> 3092 3093```c 3094napi_status napi_get_arraybuffer_info(napi_env env, 3095 napi_value arraybuffer, 3096 void** data, 3097 size_t* byte_length) 3098``` 3099 3100* `[in] env`: The environment that the API is invoked under. 3101* `[in] arraybuffer`: `napi_value` representing the `ArrayBuffer` being queried. 3102* `[out] data`: The underlying data buffer of the `ArrayBuffer`. If byte\_length 3103 is `0`, this may be `NULL` or any other pointer value. 3104* `[out] byte_length`: Length in bytes of the underlying data buffer. 3105 3106Returns `napi_ok` if the API succeeded. 3107 3108This API is used to retrieve the underlying data buffer of an `ArrayBuffer` and 3109its length. 3110 3111_WARNING_: Use caution while using this API. The lifetime of the underlying data 3112buffer is managed by the `ArrayBuffer` even after it's returned. A 3113possible safe way to use this API is in conjunction with 3114[`napi_create_reference`][], which can be used to guarantee control over the 3115lifetime of the `ArrayBuffer`. It's also safe to use the returned data buffer 3116within the same callback as long as there are no calls to other APIs that might 3117trigger a GC. 3118 3119#### `napi_get_buffer_info` 3120 3121<!-- YAML 3122added: v8.0.0 3123napiVersion: 1 3124--> 3125 3126```c 3127napi_status napi_get_buffer_info(napi_env env, 3128 napi_value value, 3129 void** data, 3130 size_t* length) 3131``` 3132 3133* `[in] env`: The environment that the API is invoked under. 3134* `[in] value`: `napi_value` representing the `node::Buffer` or `Uint8Array` 3135 being queried. 3136* `[out] data`: The underlying data buffer of the `node::Buffer` or 3137 `Uint8Array`. If length is `0`, this may be `NULL` or any other pointer value. 3138* `[out] length`: Length in bytes of the underlying data buffer. 3139 3140Returns `napi_ok` if the API succeeded. 3141 3142This method returns the identical `data` and `byte_length` as 3143[`napi_get_typedarray_info`][]. And `napi_get_typedarray_info` accepts a 3144`node::Buffer` (a Uint8Array) as the value too. 3145 3146This API is used to retrieve the underlying data buffer of a `node::Buffer` 3147and its length. 3148 3149_Warning_: Use caution while using this API since the underlying data buffer's 3150lifetime is not guaranteed if it's managed by the VM. 3151 3152#### `napi_get_prototype` 3153 3154<!-- YAML 3155added: v8.0.0 3156napiVersion: 1 3157--> 3158 3159```c 3160napi_status napi_get_prototype(napi_env env, 3161 napi_value object, 3162 napi_value* result) 3163``` 3164 3165* `[in] env`: The environment that the API is invoked under. 3166* `[in] object`: `napi_value` representing JavaScript `Object` whose prototype 3167 to return. This returns the equivalent of `Object.getPrototypeOf` (which is 3168 not the same as the function's `prototype` property). 3169* `[out] result`: `napi_value` representing prototype of the given object. 3170 3171Returns `napi_ok` if the API succeeded. 3172 3173#### `napi_get_typedarray_info` 3174 3175<!-- YAML 3176added: v8.0.0 3177napiVersion: 1 3178--> 3179 3180```c 3181napi_status napi_get_typedarray_info(napi_env env, 3182 napi_value typedarray, 3183 napi_typedarray_type* type, 3184 size_t* length, 3185 void** data, 3186 napi_value* arraybuffer, 3187 size_t* byte_offset) 3188``` 3189 3190* `[in] env`: The environment that the API is invoked under. 3191* `[in] typedarray`: `napi_value` representing the `TypedArray` whose 3192 properties to query. 3193* `[out] type`: Scalar datatype of the elements within the `TypedArray`. 3194* `[out] length`: The number of elements in the `TypedArray`. 3195* `[out] data`: The data buffer underlying the `TypedArray` adjusted by 3196 the `byte_offset` value so that it points to the first element in the 3197 `TypedArray`. If the length of the array is `0`, this may be `NULL` or 3198 any other pointer value. 3199* `[out] arraybuffer`: The `ArrayBuffer` underlying the `TypedArray`. 3200* `[out] byte_offset`: The byte offset within the underlying native array 3201 at which the first element of the arrays is located. The value for the data 3202 parameter has already been adjusted so that data points to the first element 3203 in the array. Therefore, the first byte of the native array would be at 3204 `data - byte_offset`. 3205 3206Returns `napi_ok` if the API succeeded. 3207 3208This API returns various properties of a typed array. 3209 3210Any of the out parameters may be `NULL` if that property is unneeded. 3211 3212_Warning_: Use caution while using this API since the underlying data buffer 3213is managed by the VM. 3214 3215#### `napi_get_dataview_info` 3216 3217<!-- YAML 3218added: v8.3.0 3219napiVersion: 1 3220--> 3221 3222```c 3223napi_status napi_get_dataview_info(napi_env env, 3224 napi_value dataview, 3225 size_t* byte_length, 3226 void** data, 3227 napi_value* arraybuffer, 3228 size_t* byte_offset) 3229``` 3230 3231* `[in] env`: The environment that the API is invoked under. 3232* `[in] dataview`: `napi_value` representing the `DataView` whose 3233 properties to query. 3234* `[out] byte_length`: Number of bytes in the `DataView`. 3235* `[out] data`: The data buffer underlying the `DataView`. 3236 If byte\_length is `0`, this may be `NULL` or any other pointer value. 3237* `[out] arraybuffer`: `ArrayBuffer` underlying the `DataView`. 3238* `[out] byte_offset`: The byte offset within the data buffer from which 3239 to start projecting the `DataView`. 3240 3241Returns `napi_ok` if the API succeeded. 3242 3243Any of the out parameters may be `NULL` if that property is unneeded. 3244 3245This API returns various properties of a `DataView`. 3246 3247#### `napi_get_date_value` 3248 3249<!-- YAML 3250added: 3251 - v11.11.0 3252 - v10.17.0 3253napiVersion: 5 3254--> 3255 3256```c 3257napi_status napi_get_date_value(napi_env env, 3258 napi_value value, 3259 double* result) 3260``` 3261 3262* `[in] env`: The environment that the API is invoked under. 3263* `[in] value`: `napi_value` representing a JavaScript `Date`. 3264* `[out] result`: Time value as a `double` represented as milliseconds since 3265 midnight at the beginning of 01 January, 1970 UTC. 3266 3267This API does not observe leap seconds; they are ignored, as 3268ECMAScript aligns with POSIX time specification. 3269 3270Returns `napi_ok` if the API succeeded. If a non-date `napi_value` is passed 3271in it returns `napi_date_expected`. 3272 3273This API returns the C double primitive of time value for the given JavaScript 3274`Date`. 3275 3276#### `napi_get_value_bool` 3277 3278<!-- YAML 3279added: v8.0.0 3280napiVersion: 1 3281--> 3282 3283```c 3284napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) 3285``` 3286 3287* `[in] env`: The environment that the API is invoked under. 3288* `[in] value`: `napi_value` representing JavaScript `Boolean`. 3289* `[out] result`: C boolean primitive equivalent of the given JavaScript 3290 `Boolean`. 3291 3292Returns `napi_ok` if the API succeeded. If a non-boolean `napi_value` is 3293passed in it returns `napi_boolean_expected`. 3294 3295This API returns the C boolean primitive equivalent of the given JavaScript 3296`Boolean`. 3297 3298#### `napi_get_value_double` 3299 3300<!-- YAML 3301added: v8.0.0 3302napiVersion: 1 3303--> 3304 3305```c 3306napi_status napi_get_value_double(napi_env env, 3307 napi_value value, 3308 double* result) 3309``` 3310 3311* `[in] env`: The environment that the API is invoked under. 3312* `[in] value`: `napi_value` representing JavaScript `number`. 3313* `[out] result`: C double primitive equivalent of the given JavaScript 3314 `number`. 3315 3316Returns `napi_ok` if the API succeeded. If a non-number `napi_value` is passed 3317in it returns `napi_number_expected`. 3318 3319This API returns the C double primitive equivalent of the given JavaScript 3320`number`. 3321 3322#### `napi_get_value_bigint_int64` 3323 3324<!-- YAML 3325added: v10.7.0 3326napiVersion: 6 3327--> 3328 3329```c 3330napi_status napi_get_value_bigint_int64(napi_env env, 3331 napi_value value, 3332 int64_t* result, 3333 bool* lossless); 3334``` 3335 3336* `[in] env`: The environment that the API is invoked under 3337* `[in] value`: `napi_value` representing JavaScript `BigInt`. 3338* `[out] result`: C `int64_t` primitive equivalent of the given JavaScript 3339 `BigInt`. 3340* `[out] lossless`: Indicates whether the `BigInt` value was converted 3341 losslessly. 3342 3343Returns `napi_ok` if the API succeeded. If a non-`BigInt` is passed in it 3344returns `napi_bigint_expected`. 3345 3346This API returns the C `int64_t` primitive equivalent of the given JavaScript 3347`BigInt`. If needed it will truncate the value, setting `lossless` to `false`. 3348 3349#### `napi_get_value_bigint_uint64` 3350 3351<!-- YAML 3352added: v10.7.0 3353napiVersion: 6 3354--> 3355 3356```c 3357napi_status napi_get_value_bigint_uint64(napi_env env, 3358 napi_value value, 3359 uint64_t* result, 3360 bool* lossless); 3361``` 3362 3363* `[in] env`: The environment that the API is invoked under. 3364* `[in] value`: `napi_value` representing JavaScript `BigInt`. 3365* `[out] result`: C `uint64_t` primitive equivalent of the given JavaScript 3366 `BigInt`. 3367* `[out] lossless`: Indicates whether the `BigInt` value was converted 3368 losslessly. 3369 3370Returns `napi_ok` if the API succeeded. If a non-`BigInt` is passed in it 3371returns `napi_bigint_expected`. 3372 3373This API returns the C `uint64_t` primitive equivalent of the given JavaScript 3374`BigInt`. If needed it will truncate the value, setting `lossless` to `false`. 3375 3376#### `napi_get_value_bigint_words` 3377 3378<!-- YAML 3379added: v10.7.0 3380napiVersion: 6 3381--> 3382 3383```c 3384napi_status napi_get_value_bigint_words(napi_env env, 3385 napi_value value, 3386 int* sign_bit, 3387 size_t* word_count, 3388 uint64_t* words); 3389``` 3390 3391* `[in] env`: The environment that the API is invoked under. 3392* `[in] value`: `napi_value` representing JavaScript `BigInt`. 3393* `[out] sign_bit`: Integer representing if the JavaScript `BigInt` is positive 3394 or negative. 3395* `[in/out] word_count`: Must be initialized to the length of the `words` 3396 array. Upon return, it will be set to the actual number of words that 3397 would be needed to store this `BigInt`. 3398* `[out] words`: Pointer to a pre-allocated 64-bit word array. 3399 3400Returns `napi_ok` if the API succeeded. 3401 3402This API converts a single `BigInt` value into a sign bit, 64-bit little-endian 3403array, and the number of elements in the array. `sign_bit` and `words` may be 3404both set to `NULL`, in order to get only `word_count`. 3405 3406#### `napi_get_value_external` 3407 3408<!-- YAML 3409added: v8.0.0 3410napiVersion: 1 3411--> 3412 3413```c 3414napi_status napi_get_value_external(napi_env env, 3415 napi_value value, 3416 void** result) 3417``` 3418 3419* `[in] env`: The environment that the API is invoked under. 3420* `[in] value`: `napi_value` representing JavaScript external value. 3421* `[out] result`: Pointer to the data wrapped by the JavaScript external value. 3422 3423Returns `napi_ok` if the API succeeded. If a non-external `napi_value` is 3424passed in it returns `napi_invalid_arg`. 3425 3426This API retrieves the external data pointer that was previously passed to 3427`napi_create_external()`. 3428 3429#### `napi_get_value_int32` 3430 3431<!-- YAML 3432added: v8.0.0 3433napiVersion: 1 3434--> 3435 3436```c 3437napi_status napi_get_value_int32(napi_env env, 3438 napi_value value, 3439 int32_t* result) 3440``` 3441 3442* `[in] env`: The environment that the API is invoked under. 3443* `[in] value`: `napi_value` representing JavaScript `number`. 3444* `[out] result`: C `int32` primitive equivalent of the given JavaScript 3445 `number`. 3446 3447Returns `napi_ok` if the API succeeded. If a non-number `napi_value` 3448is passed in `napi_number_expected`. 3449 3450This API returns the C `int32` primitive equivalent 3451of the given JavaScript `number`. 3452 3453If the number exceeds the range of the 32 bit integer, then the result is 3454truncated to the equivalent of the bottom 32 bits. This can result in a large 3455positive number becoming a negative number if the value is > 2<sup>31</sup> - 1. 3456 3457Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the 3458result to zero. 3459 3460#### `napi_get_value_int64` 3461 3462<!-- YAML 3463added: v8.0.0 3464napiVersion: 1 3465--> 3466 3467```c 3468napi_status napi_get_value_int64(napi_env env, 3469 napi_value value, 3470 int64_t* result) 3471``` 3472 3473* `[in] env`: The environment that the API is invoked under. 3474* `[in] value`: `napi_value` representing JavaScript `number`. 3475* `[out] result`: C `int64` primitive equivalent of the given JavaScript 3476 `number`. 3477 3478Returns `napi_ok` if the API succeeded. If a non-number `napi_value` 3479is passed in it returns `napi_number_expected`. 3480 3481This API returns the C `int64` primitive equivalent of the given JavaScript 3482`number`. 3483 3484`number` values outside the range of [`Number.MIN_SAFE_INTEGER`][] 3485`-(2**53 - 1)` - [`Number.MAX_SAFE_INTEGER`][] `(2**53 - 1)` will lose 3486precision. 3487 3488Non-finite number values (`NaN`, `+Infinity`, or `-Infinity`) set the 3489result to zero. 3490 3491#### `napi_get_value_string_latin1` 3492 3493<!-- YAML 3494added: v8.0.0 3495napiVersion: 1 3496--> 3497 3498```c 3499napi_status napi_get_value_string_latin1(napi_env env, 3500 napi_value value, 3501 char* buf, 3502 size_t bufsize, 3503 size_t* result) 3504``` 3505 3506* `[in] env`: The environment that the API is invoked under. 3507* `[in] value`: `napi_value` representing JavaScript string. 3508* `[in] buf`: Buffer to write the ISO-8859-1-encoded string into. If `NULL` is 3509 passed in, the length of the string in bytes and excluding the null terminator 3510 is returned in `result`. 3511* `[in] bufsize`: Size of the destination buffer. When this value is 3512 insufficient, the returned string is truncated and null-terminated. 3513* `[out] result`: Number of bytes copied into the buffer, excluding the null 3514 terminator. 3515 3516Returns `napi_ok` if the API succeeded. If a non-`string` `napi_value` 3517is passed in it returns `napi_string_expected`. 3518 3519This API returns the ISO-8859-1-encoded string corresponding the value passed 3520in. 3521 3522#### `napi_get_value_string_utf8` 3523 3524<!-- YAML 3525added: v8.0.0 3526napiVersion: 1 3527--> 3528 3529```c 3530napi_status napi_get_value_string_utf8(napi_env env, 3531 napi_value value, 3532 char* buf, 3533 size_t bufsize, 3534 size_t* result) 3535``` 3536 3537* `[in] env`: The environment that the API is invoked under. 3538* `[in] value`: `napi_value` representing JavaScript string. 3539* `[in] buf`: Buffer to write the UTF8-encoded string into. If `NULL` is passed 3540 in, the length of the string in bytes and excluding the null terminator is 3541 returned in `result`. 3542* `[in] bufsize`: Size of the destination buffer. When this value is 3543 insufficient, the returned string is truncated and null-terminated. 3544* `[out] result`: Number of bytes copied into the buffer, excluding the null 3545 terminator. 3546 3547Returns `napi_ok` if the API succeeded. If a non-`string` `napi_value` 3548is passed in it returns `napi_string_expected`. 3549 3550This API returns the UTF8-encoded string corresponding the value passed in. 3551 3552#### `napi_get_value_string_utf16` 3553 3554<!-- YAML 3555added: v8.0.0 3556napiVersion: 1 3557--> 3558 3559```c 3560napi_status napi_get_value_string_utf16(napi_env env, 3561 napi_value value, 3562 char16_t* buf, 3563 size_t bufsize, 3564 size_t* result) 3565``` 3566 3567* `[in] env`: The environment that the API is invoked under. 3568* `[in] value`: `napi_value` representing JavaScript string. 3569* `[in] buf`: Buffer to write the UTF16-LE-encoded string into. If `NULL` is 3570 passed in, the length of the string in 2-byte code units and excluding the 3571 null terminator is returned. 3572* `[in] bufsize`: Size of the destination buffer. When this value is 3573 insufficient, the returned string is truncated and null-terminated. 3574* `[out] result`: Number of 2-byte code units copied into the buffer, excluding 3575 the null terminator. 3576 3577Returns `napi_ok` if the API succeeded. If a non-`string` `napi_value` 3578is passed in it returns `napi_string_expected`. 3579 3580This API returns the UTF16-encoded string corresponding the value passed in. 3581 3582#### `napi_get_value_uint32` 3583 3584<!-- YAML 3585added: v8.0.0 3586napiVersion: 1 3587--> 3588 3589```c 3590napi_status napi_get_value_uint32(napi_env env, 3591 napi_value value, 3592 uint32_t* result) 3593``` 3594 3595* `[in] env`: The environment that the API is invoked under. 3596* `[in] value`: `napi_value` representing JavaScript `number`. 3597* `[out] result`: C primitive equivalent of the given `napi_value` as a 3598 `uint32_t`. 3599 3600Returns `napi_ok` if the API succeeded. If a non-number `napi_value` 3601is passed in it returns `napi_number_expected`. 3602 3603This API returns the C primitive equivalent of the given `napi_value` as a 3604`uint32_t`. 3605 3606### Functions to get global instances 3607 3608#### `napi_get_boolean` 3609 3610<!-- YAML 3611added: v8.0.0 3612napiVersion: 1 3613--> 3614 3615```c 3616napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) 3617``` 3618 3619* `[in] env`: The environment that the API is invoked under. 3620* `[in] value`: The value of the boolean to retrieve. 3621* `[out] result`: `napi_value` representing JavaScript `Boolean` singleton to 3622 retrieve. 3623 3624Returns `napi_ok` if the API succeeded. 3625 3626This API is used to return the JavaScript singleton object that is used to 3627represent the given boolean value. 3628 3629#### `napi_get_global` 3630 3631<!-- YAML 3632added: v8.0.0 3633napiVersion: 1 3634--> 3635 3636```c 3637napi_status napi_get_global(napi_env env, napi_value* result) 3638``` 3639 3640* `[in] env`: The environment that the API is invoked under. 3641* `[out] result`: `napi_value` representing JavaScript `global` object. 3642 3643Returns `napi_ok` if the API succeeded. 3644 3645This API returns the `global` object. 3646 3647#### `napi_get_null` 3648 3649<!-- YAML 3650added: v8.0.0 3651napiVersion: 1 3652--> 3653 3654```c 3655napi_status napi_get_null(napi_env env, napi_value* result) 3656``` 3657 3658* `[in] env`: The environment that the API is invoked under. 3659* `[out] result`: `napi_value` representing JavaScript `null` object. 3660 3661Returns `napi_ok` if the API succeeded. 3662 3663This API returns the `null` object. 3664 3665#### `napi_get_undefined` 3666 3667<!-- YAML 3668added: v8.0.0 3669napiVersion: 1 3670--> 3671 3672```c 3673napi_status napi_get_undefined(napi_env env, napi_value* result) 3674``` 3675 3676* `[in] env`: The environment that the API is invoked under. 3677* `[out] result`: `napi_value` representing JavaScript Undefined value. 3678 3679Returns `napi_ok` if the API succeeded. 3680 3681This API returns the Undefined object. 3682 3683## Working with JavaScript values and abstract operations 3684 3685Node-API exposes a set of APIs to perform some abstract operations on JavaScript 3686values. Some of these operations are documented under [Section 7][] 3687of the [ECMAScript Language Specification][]. 3688 3689These APIs support doing one of the following: 3690 36911. Coerce JavaScript values to specific JavaScript types (such as `number` or 3692 `string`). 36932. Check the type of a JavaScript value. 36943. Check for equality between two JavaScript values. 3695 3696### `napi_coerce_to_bool` 3697 3698<!-- YAML 3699added: v8.0.0 3700napiVersion: 1 3701--> 3702 3703```c 3704napi_status napi_coerce_to_bool(napi_env env, 3705 napi_value value, 3706 napi_value* result) 3707``` 3708 3709* `[in] env`: The environment that the API is invoked under. 3710* `[in] value`: The JavaScript value to coerce. 3711* `[out] result`: `napi_value` representing the coerced JavaScript `Boolean`. 3712 3713Returns `napi_ok` if the API succeeded. 3714 3715This API implements the abstract operation `ToBoolean()` as defined in 3716[Section 7.1.2][] of the ECMAScript Language Specification. 3717 3718### `napi_coerce_to_number` 3719 3720<!-- YAML 3721added: v8.0.0 3722napiVersion: 1 3723--> 3724 3725```c 3726napi_status napi_coerce_to_number(napi_env env, 3727 napi_value value, 3728 napi_value* result) 3729``` 3730 3731* `[in] env`: The environment that the API is invoked under. 3732* `[in] value`: The JavaScript value to coerce. 3733* `[out] result`: `napi_value` representing the coerced JavaScript `number`. 3734 3735Returns `napi_ok` if the API succeeded. 3736 3737This API implements the abstract operation `ToNumber()` as defined in 3738[Section 7.1.3][] of the ECMAScript Language Specification. 3739This function potentially runs JS code if the passed-in value is an 3740object. 3741 3742### `napi_coerce_to_object` 3743 3744<!-- YAML 3745added: v8.0.0 3746napiVersion: 1 3747--> 3748 3749```c 3750napi_status napi_coerce_to_object(napi_env env, 3751 napi_value value, 3752 napi_value* result) 3753``` 3754 3755* `[in] env`: The environment that the API is invoked under. 3756* `[in] value`: The JavaScript value to coerce. 3757* `[out] result`: `napi_value` representing the coerced JavaScript `Object`. 3758 3759Returns `napi_ok` if the API succeeded. 3760 3761This API implements the abstract operation `ToObject()` as defined in 3762[Section 7.1.13][] of the ECMAScript Language Specification. 3763 3764### `napi_coerce_to_string` 3765 3766<!-- YAML 3767added: v8.0.0 3768napiVersion: 1 3769--> 3770 3771```c 3772napi_status napi_coerce_to_string(napi_env env, 3773 napi_value value, 3774 napi_value* result) 3775``` 3776 3777* `[in] env`: The environment that the API is invoked under. 3778* `[in] value`: The JavaScript value to coerce. 3779* `[out] result`: `napi_value` representing the coerced JavaScript `string`. 3780 3781Returns `napi_ok` if the API succeeded. 3782 3783This API implements the abstract operation `ToString()` as defined in 3784[Section 7.1.13][] of the ECMAScript Language Specification. 3785This function potentially runs JS code if the passed-in value is an 3786object. 3787 3788### `napi_typeof` 3789 3790<!-- YAML 3791added: v8.0.0 3792napiVersion: 1 3793--> 3794 3795```c 3796napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result) 3797``` 3798 3799* `[in] env`: The environment that the API is invoked under. 3800* `[in] value`: The JavaScript value whose type to query. 3801* `[out] result`: The type of the JavaScript value. 3802 3803Returns `napi_ok` if the API succeeded. 3804 3805* `napi_invalid_arg` if the type of `value` is not a known ECMAScript type and 3806 `value` is not an External value. 3807 3808This API represents behavior similar to invoking the `typeof` Operator on 3809the object as defined in [Section 12.5.5][] of the ECMAScript Language 3810Specification. However, there are some differences: 3811 38121. It has support for detecting an External value. 38132. It detects `null` as a separate type, while ECMAScript `typeof` would detect 3814 `object`. 3815 3816If `value` has a type that is invalid, an error is returned. 3817 3818### `napi_instanceof` 3819 3820<!-- YAML 3821added: v8.0.0 3822napiVersion: 1 3823--> 3824 3825```c 3826napi_status napi_instanceof(napi_env env, 3827 napi_value object, 3828 napi_value constructor, 3829 bool* result) 3830``` 3831 3832* `[in] env`: The environment that the API is invoked under. 3833* `[in] object`: The JavaScript value to check. 3834* `[in] constructor`: The JavaScript function object of the constructor function 3835 to check against. 3836* `[out] result`: Boolean that is set to true if `object instanceof constructor` 3837 is true. 3838 3839Returns `napi_ok` if the API succeeded. 3840 3841This API represents invoking the `instanceof` Operator on the object as 3842defined in [Section 12.10.4][] of the ECMAScript Language Specification. 3843 3844### `napi_is_array` 3845 3846<!-- YAML 3847added: v8.0.0 3848napiVersion: 1 3849--> 3850 3851```c 3852napi_status napi_is_array(napi_env env, napi_value value, bool* result) 3853``` 3854 3855* `[in] env`: The environment that the API is invoked under. 3856* `[in] value`: The JavaScript value to check. 3857* `[out] result`: Whether the given object is an array. 3858 3859Returns `napi_ok` if the API succeeded. 3860 3861This API represents invoking the `IsArray` operation on the object 3862as defined in [Section 7.2.2][] of the ECMAScript Language Specification. 3863 3864### `napi_is_arraybuffer` 3865 3866<!-- YAML 3867added: v8.0.0 3868napiVersion: 1 3869--> 3870 3871```c 3872napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result) 3873``` 3874 3875* `[in] env`: The environment that the API is invoked under. 3876* `[in] value`: The JavaScript value to check. 3877* `[out] result`: Whether the given object is an `ArrayBuffer`. 3878 3879Returns `napi_ok` if the API succeeded. 3880 3881This API checks if the `Object` passed in is an array buffer. 3882 3883### `napi_is_buffer` 3884 3885<!-- YAML 3886added: v8.0.0 3887napiVersion: 1 3888--> 3889 3890```c 3891napi_status napi_is_buffer(napi_env env, napi_value value, bool* result) 3892``` 3893 3894* `[in] env`: The environment that the API is invoked under. 3895* `[in] value`: The JavaScript value to check. 3896* `[out] result`: Whether the given `napi_value` represents a `node::Buffer` or 3897 `Uint8Array` object. 3898 3899Returns `napi_ok` if the API succeeded. 3900 3901This API checks if the `Object` passed in is a buffer or Uint8Array. 3902[`napi_is_typedarray`][] should be preferred if the caller needs to check if the 3903value is a Uint8Array. 3904 3905### `napi_is_date` 3906 3907<!-- YAML 3908added: 3909 - v11.11.0 3910 - v10.17.0 3911napiVersion: 5 3912--> 3913 3914```c 3915napi_status napi_is_date(napi_env env, napi_value value, bool* result) 3916``` 3917 3918* `[in] env`: The environment that the API is invoked under. 3919* `[in] value`: The JavaScript value to check. 3920* `[out] result`: Whether the given `napi_value` represents a JavaScript `Date` 3921 object. 3922 3923Returns `napi_ok` if the API succeeded. 3924 3925This API checks if the `Object` passed in is a date. 3926 3927### `napi_is_error` 3928 3929<!-- YAML 3930added: v8.0.0 3931napiVersion: 1 3932--> 3933 3934```c 3935napi_status napi_is_error(napi_env env, napi_value value, bool* result) 3936``` 3937 3938* `[in] env`: The environment that the API is invoked under. 3939* `[in] value`: The JavaScript value to check. 3940* `[out] result`: Whether the given `napi_value` represents an `Error` object. 3941 3942Returns `napi_ok` if the API succeeded. 3943 3944This API checks if the `Object` passed in is an `Error`. 3945 3946### `napi_is_typedarray` 3947 3948<!-- YAML 3949added: v8.0.0 3950napiVersion: 1 3951--> 3952 3953```c 3954napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result) 3955``` 3956 3957* `[in] env`: The environment that the API is invoked under. 3958* `[in] value`: The JavaScript value to check. 3959* `[out] result`: Whether the given `napi_value` represents a `TypedArray`. 3960 3961Returns `napi_ok` if the API succeeded. 3962 3963This API checks if the `Object` passed in is a typed array. 3964 3965### `napi_is_dataview` 3966 3967<!-- YAML 3968added: v8.3.0 3969napiVersion: 1 3970--> 3971 3972```c 3973napi_status napi_is_dataview(napi_env env, napi_value value, bool* result) 3974``` 3975 3976* `[in] env`: The environment that the API is invoked under. 3977* `[in] value`: The JavaScript value to check. 3978* `[out] result`: Whether the given `napi_value` represents a `DataView`. 3979 3980Returns `napi_ok` if the API succeeded. 3981 3982This API checks if the `Object` passed in is a `DataView`. 3983 3984### `napi_strict_equals` 3985 3986<!-- YAML 3987added: v8.0.0 3988napiVersion: 1 3989--> 3990 3991```c 3992napi_status napi_strict_equals(napi_env env, 3993 napi_value lhs, 3994 napi_value rhs, 3995 bool* result) 3996``` 3997 3998* `[in] env`: The environment that the API is invoked under. 3999* `[in] lhs`: The JavaScript value to check. 4000* `[in] rhs`: The JavaScript value to check against. 4001* `[out] result`: Whether the two `napi_value` objects are equal. 4002 4003Returns `napi_ok` if the API succeeded. 4004 4005This API represents the invocation of the Strict Equality algorithm as 4006defined in [Section 7.2.14][] of the ECMAScript Language Specification. 4007 4008### `napi_detach_arraybuffer` 4009 4010<!-- YAML 4011added: 4012 - v13.0.0 4013 - v12.16.0 4014 - v10.22.0 4015napiVersion: 7 4016--> 4017 4018```c 4019napi_status napi_detach_arraybuffer(napi_env env, 4020 napi_value arraybuffer) 4021``` 4022 4023* `[in] env`: The environment that the API is invoked under. 4024* `[in] arraybuffer`: The JavaScript `ArrayBuffer` to be detached. 4025 4026Returns `napi_ok` if the API succeeded. If a non-detachable `ArrayBuffer` is 4027passed in it returns `napi_detachable_arraybuffer_expected`. 4028 4029Generally, an `ArrayBuffer` is non-detachable if it has been detached before. 4030The engine may impose additional conditions on whether an `ArrayBuffer` is 4031detachable. For example, V8 requires that the `ArrayBuffer` be external, 4032that is, created with [`napi_create_external_arraybuffer`][]. 4033 4034This API represents the invocation of the `ArrayBuffer` detach operation as 4035defined in [Section 24.1.1.3][] of the ECMAScript Language Specification. 4036 4037### `napi_is_detached_arraybuffer` 4038 4039<!-- YAML 4040added: 4041 - v13.3.0 4042 - v12.16.0 4043 - v10.22.0 4044napiVersion: 7 4045--> 4046 4047```c 4048napi_status napi_is_detached_arraybuffer(napi_env env, 4049 napi_value arraybuffer, 4050 bool* result) 4051``` 4052 4053* `[in] env`: The environment that the API is invoked under. 4054* `[in] arraybuffer`: The JavaScript `ArrayBuffer` to be checked. 4055* `[out] result`: Whether the `arraybuffer` is detached. 4056 4057Returns `napi_ok` if the API succeeded. 4058 4059The `ArrayBuffer` is considered detached if its internal data is `null`. 4060 4061This API represents the invocation of the `ArrayBuffer` `IsDetachedBuffer` 4062operation as defined in [Section 24.1.1.2][] of the ECMAScript Language 4063Specification. 4064 4065## Working with JavaScript properties 4066 4067Node-API exposes a set of APIs to get and set properties on JavaScript 4068objects. Some of these types are documented under [Section 7][] of the 4069[ECMAScript Language Specification][]. 4070 4071Properties in JavaScript are represented as a tuple of a key and a value. 4072Fundamentally, all property keys in Node-API can be represented in one of the 4073following forms: 4074 4075* Named: a simple UTF8-encoded string 4076* Integer-Indexed: an index value represented by `uint32_t` 4077* JavaScript value: these are represented in Node-API by `napi_value`. This can 4078 be a `napi_value` representing a `string`, `number`, or `symbol`. 4079 4080Node-API values are represented by the type `napi_value`. 4081Any Node-API call that requires a JavaScript value takes in a `napi_value`. 4082However, it's the caller's responsibility to make sure that the 4083`napi_value` in question is of the JavaScript type expected by the API. 4084 4085The APIs documented in this section provide a simple interface to 4086get and set properties on arbitrary JavaScript objects represented by 4087`napi_value`. 4088 4089For instance, consider the following JavaScript code snippet: 4090 4091```js 4092const obj = {}; 4093obj.myProp = 123; 4094``` 4095 4096The equivalent can be done using Node-API values with the following snippet: 4097 4098```c 4099napi_status status = napi_generic_failure; 4100 4101// const obj = {} 4102napi_value obj, value; 4103status = napi_create_object(env, &obj); 4104if (status != napi_ok) return status; 4105 4106// Create a napi_value for 123 4107status = napi_create_int32(env, 123, &value); 4108if (status != napi_ok) return status; 4109 4110// obj.myProp = 123 4111status = napi_set_named_property(env, obj, "myProp", value); 4112if (status != napi_ok) return status; 4113``` 4114 4115Indexed properties can be set in a similar manner. Consider the following 4116JavaScript snippet: 4117 4118```js 4119const arr = []; 4120arr[123] = 'hello'; 4121``` 4122 4123The equivalent can be done using Node-API values with the following snippet: 4124 4125```c 4126napi_status status = napi_generic_failure; 4127 4128// const arr = []; 4129napi_value arr, value; 4130status = napi_create_array(env, &arr); 4131if (status != napi_ok) return status; 4132 4133// Create a napi_value for 'hello' 4134status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &value); 4135if (status != napi_ok) return status; 4136 4137// arr[123] = 'hello'; 4138status = napi_set_element(env, arr, 123, value); 4139if (status != napi_ok) return status; 4140``` 4141 4142Properties can be retrieved using the APIs described in this section. 4143Consider the following JavaScript snippet: 4144 4145```js 4146const arr = []; 4147const value = arr[123]; 4148``` 4149 4150The following is the approximate equivalent of the Node-API counterpart: 4151 4152```c 4153napi_status status = napi_generic_failure; 4154 4155// const arr = [] 4156napi_value arr, value; 4157status = napi_create_array(env, &arr); 4158if (status != napi_ok) return status; 4159 4160// const value = arr[123] 4161status = napi_get_element(env, arr, 123, &value); 4162if (status != napi_ok) return status; 4163``` 4164 4165Finally, multiple properties can also be defined on an object for performance 4166reasons. Consider the following JavaScript: 4167 4168```js 4169const obj = {}; 4170Object.defineProperties(obj, { 4171 'foo': { value: 123, writable: true, configurable: true, enumerable: true }, 4172 'bar': { value: 456, writable: true, configurable: true, enumerable: true }, 4173}); 4174``` 4175 4176The following is the approximate equivalent of the Node-API counterpart: 4177 4178```c 4179napi_status status = napi_status_generic_failure; 4180 4181// const obj = {}; 4182napi_value obj; 4183status = napi_create_object(env, &obj); 4184if (status != napi_ok) return status; 4185 4186// Create napi_values for 123 and 456 4187napi_value fooValue, barValue; 4188status = napi_create_int32(env, 123, &fooValue); 4189if (status != napi_ok) return status; 4190status = napi_create_int32(env, 456, &barValue); 4191if (status != napi_ok) return status; 4192 4193// Set the properties 4194napi_property_descriptor descriptors[] = { 4195 { "foo", NULL, NULL, NULL, NULL, fooValue, napi_writable | napi_configurable, NULL }, 4196 { "bar", NULL, NULL, NULL, NULL, barValue, napi_writable | napi_configurable, NULL } 4197} 4198status = napi_define_properties(env, 4199 obj, 4200 sizeof(descriptors) / sizeof(descriptors[0]), 4201 descriptors); 4202if (status != napi_ok) return status; 4203``` 4204 4205### Structures 4206 4207#### `napi_property_attributes` 4208 4209<!-- YAML 4210changes: 4211 - version: v14.12.0 4212 pr-url: https://github.com/nodejs/node/pull/35214 4213 description: added `napi_default_method` and `napi_default_property`. 4214--> 4215 4216```c 4217typedef enum { 4218 napi_default = 0, 4219 napi_writable = 1 << 0, 4220 napi_enumerable = 1 << 1, 4221 napi_configurable = 1 << 2, 4222 4223 // Used with napi_define_class to distinguish static properties 4224 // from instance properties. Ignored by napi_define_properties. 4225 napi_static = 1 << 10, 4226 4227 // Default for class methods. 4228 napi_default_method = napi_writable | napi_configurable, 4229 4230 // Default for object properties, like in JS obj[prop]. 4231 napi_default_jsproperty = napi_writable | 4232 napi_enumerable | 4233 napi_configurable, 4234} napi_property_attributes; 4235``` 4236 4237`napi_property_attributes` are flags used to control the behavior of properties 4238set on a JavaScript object. Other than `napi_static` they correspond to the 4239attributes listed in [Section 6.1.7.1][] 4240of the [ECMAScript Language Specification][]. 4241They can be one or more of the following bitflags: 4242 4243* `napi_default`: No explicit attributes are set on the property. By default, a 4244 property is read only, not enumerable and not configurable. 4245* `napi_writable`: The property is writable. 4246* `napi_enumerable`: The property is enumerable. 4247* `napi_configurable`: The property is configurable as defined in 4248 [Section 6.1.7.1][] of the [ECMAScript Language Specification][]. 4249* `napi_static`: The property will be defined as a static property on a class as 4250 opposed to an instance property, which is the default. This is used only by 4251 [`napi_define_class`][]. It is ignored by `napi_define_properties`. 4252* `napi_default_method`: Like a method in a JS class, the property is 4253 configurable and writeable, but not enumerable. 4254* `napi_default_jsproperty`: Like a property set via assignment in JavaScript, 4255 the property is writable, enumerable, and configurable. 4256 4257#### `napi_property_descriptor` 4258 4259```c 4260typedef struct { 4261 // One of utf8name or name should be NULL. 4262 const char* utf8name; 4263 napi_value name; 4264 4265 napi_callback method; 4266 napi_callback getter; 4267 napi_callback setter; 4268 napi_value value; 4269 4270 napi_property_attributes attributes; 4271 void* data; 4272} napi_property_descriptor; 4273``` 4274 4275* `utf8name`: Optional string describing the key for the property, 4276 encoded as UTF8. One of `utf8name` or `name` must be provided for the 4277 property. 4278* `name`: Optional `napi_value` that points to a JavaScript string or symbol 4279 to be used as the key for the property. One of `utf8name` or `name` must 4280 be provided for the property. 4281* `value`: The value that's retrieved by a get access of the property if the 4282 property is a data property. If this is passed in, set `getter`, `setter`, 4283 `method` and `data` to `NULL` (since these members won't be used). 4284* `getter`: A function to call when a get access of the property is performed. 4285 If this is passed in, set `value` and `method` to `NULL` (since these members 4286 won't be used). The given function is called implicitly by the runtime when 4287 the property is accessed from JavaScript code (or if a get on the property is 4288 performed using a Node-API call). [`napi_callback`][] provides more details. 4289* `setter`: A function to call when a set access of the property is performed. 4290 If this is passed in, set `value` and `method` to `NULL` (since these members 4291 won't be used). The given function is called implicitly by the runtime when 4292 the property is set from JavaScript code (or if a set on the property is 4293 performed using a Node-API call). [`napi_callback`][] provides more details. 4294* `method`: Set this to make the property descriptor object's `value` 4295 property to be a JavaScript function represented by `method`. If this is 4296 passed in, set `value`, `getter` and `setter` to `NULL` (since these members 4297 won't be used). [`napi_callback`][] provides more details. 4298* `attributes`: The attributes associated with the particular property. See 4299 [`napi_property_attributes`][]. 4300* `data`: The callback data passed into `method`, `getter` and `setter` if this 4301 function is invoked. 4302 4303### Functions 4304 4305#### `napi_get_property_names` 4306 4307<!-- YAML 4308added: v8.0.0 4309napiVersion: 1 4310--> 4311 4312```c 4313napi_status napi_get_property_names(napi_env env, 4314 napi_value object, 4315 napi_value* result); 4316``` 4317 4318* `[in] env`: The environment that the Node-API call is invoked under. 4319* `[in] object`: The object from which to retrieve the properties. 4320* `[out] result`: A `napi_value` representing an array of JavaScript values 4321 that represent the property names of the object. The API can be used to 4322 iterate over `result` using [`napi_get_array_length`][] 4323 and [`napi_get_element`][]. 4324 4325Returns `napi_ok` if the API succeeded. 4326 4327This API returns the names of the enumerable properties of `object` as an array 4328of strings. The properties of `object` whose key is a symbol will not be 4329included. 4330 4331#### `napi_get_all_property_names` 4332 4333<!-- YAML 4334added: 4335 - v13.7.0 4336 - v12.17.0 4337 - v10.20.0 4338napiVersion: 6 4339--> 4340 4341```c 4342napi_get_all_property_names(napi_env env, 4343 napi_value object, 4344 napi_key_collection_mode key_mode, 4345 napi_key_filter key_filter, 4346 napi_key_conversion key_conversion, 4347 napi_value* result); 4348``` 4349 4350* `[in] env`: The environment that the Node-API call is invoked under. 4351* `[in] object`: The object from which to retrieve the properties. 4352* `[in] key_mode`: Whether to retrieve prototype properties as well. 4353* `[in] key_filter`: Which properties to retrieve 4354 (enumerable/readable/writable). 4355* `[in] key_conversion`: Whether to convert numbered property keys to strings. 4356* `[out] result`: A `napi_value` representing an array of JavaScript values 4357 that represent the property names of the object. [`napi_get_array_length`][] 4358 and [`napi_get_element`][] can be used to iterate over `result`. 4359 4360Returns `napi_ok` if the API succeeded. 4361 4362This API returns an array containing the names of the available properties 4363of this object. 4364 4365#### `napi_set_property` 4366 4367<!-- YAML 4368added: v8.0.0 4369napiVersion: 1 4370--> 4371 4372```c 4373napi_status napi_set_property(napi_env env, 4374 napi_value object, 4375 napi_value key, 4376 napi_value value); 4377``` 4378 4379* `[in] env`: The environment that the Node-API call is invoked under. 4380* `[in] object`: The object on which to set the property. 4381* `[in] key`: The name of the property to set. 4382* `[in] value`: The property value. 4383 4384Returns `napi_ok` if the API succeeded. 4385 4386This API set a property on the `Object` passed in. 4387 4388#### `napi_get_property` 4389 4390<!-- YAML 4391added: v8.0.0 4392napiVersion: 1 4393--> 4394 4395```c 4396napi_status napi_get_property(napi_env env, 4397 napi_value object, 4398 napi_value key, 4399 napi_value* result); 4400``` 4401 4402* `[in] env`: The environment that the Node-API call is invoked under. 4403* `[in] object`: The object from which to retrieve the property. 4404* `[in] key`: The name of the property to retrieve. 4405* `[out] result`: The value of the property. 4406 4407Returns `napi_ok` if the API succeeded. 4408 4409This API gets the requested property from the `Object` passed in. 4410 4411#### `napi_has_property` 4412 4413<!-- YAML 4414added: v8.0.0 4415napiVersion: 1 4416--> 4417 4418```c 4419napi_status napi_has_property(napi_env env, 4420 napi_value object, 4421 napi_value key, 4422 bool* result); 4423``` 4424 4425* `[in] env`: The environment that the Node-API call is invoked under. 4426* `[in] object`: The object to query. 4427* `[in] key`: The name of the property whose existence to check. 4428* `[out] result`: Whether the property exists on the object or not. 4429 4430Returns `napi_ok` if the API succeeded. 4431 4432This API checks if the `Object` passed in has the named property. 4433 4434#### `napi_delete_property` 4435 4436<!-- YAML 4437added: v8.2.0 4438napiVersion: 1 4439--> 4440 4441```c 4442napi_status napi_delete_property(napi_env env, 4443 napi_value object, 4444 napi_value key, 4445 bool* result); 4446``` 4447 4448* `[in] env`: The environment that the Node-API call is invoked under. 4449* `[in] object`: The object to query. 4450* `[in] key`: The name of the property to delete. 4451* `[out] result`: Whether the property deletion succeeded or not. `result` can 4452 optionally be ignored by passing `NULL`. 4453 4454Returns `napi_ok` if the API succeeded. 4455 4456This API attempts to delete the `key` own property from `object`. 4457 4458#### `napi_has_own_property` 4459 4460<!-- YAML 4461added: v8.2.0 4462napiVersion: 1 4463--> 4464 4465```c 4466napi_status napi_has_own_property(napi_env env, 4467 napi_value object, 4468 napi_value key, 4469 bool* result); 4470``` 4471 4472* `[in] env`: The environment that the Node-API call is invoked under. 4473* `[in] object`: The object to query. 4474* `[in] key`: The name of the own property whose existence to check. 4475* `[out] result`: Whether the own property exists on the object or not. 4476 4477Returns `napi_ok` if the API succeeded. 4478 4479This API checks if the `Object` passed in has the named own property. `key` must 4480be a `string` or a `symbol`, or an error will be thrown. Node-API will not 4481perform any conversion between data types. 4482 4483#### `napi_set_named_property` 4484 4485<!-- YAML 4486added: v8.0.0 4487napiVersion: 1 4488--> 4489 4490```c 4491napi_status napi_set_named_property(napi_env env, 4492 napi_value object, 4493 const char* utf8Name, 4494 napi_value value); 4495``` 4496 4497* `[in] env`: The environment that the Node-API call is invoked under. 4498* `[in] object`: The object on which to set the property. 4499* `[in] utf8Name`: The name of the property to set. 4500* `[in] value`: The property value. 4501 4502Returns `napi_ok` if the API succeeded. 4503 4504This method is equivalent to calling [`napi_set_property`][] with a `napi_value` 4505created from the string passed in as `utf8Name`. 4506 4507#### `napi_get_named_property` 4508 4509<!-- YAML 4510added: v8.0.0 4511napiVersion: 1 4512--> 4513 4514```c 4515napi_status napi_get_named_property(napi_env env, 4516 napi_value object, 4517 const char* utf8Name, 4518 napi_value* result); 4519``` 4520 4521* `[in] env`: The environment that the Node-API call is invoked under. 4522* `[in] object`: The object from which to retrieve the property. 4523* `[in] utf8Name`: The name of the property to get. 4524* `[out] result`: The value of the property. 4525 4526Returns `napi_ok` if the API succeeded. 4527 4528This method is equivalent to calling [`napi_get_property`][] with a `napi_value` 4529created from the string passed in as `utf8Name`. 4530 4531#### `napi_has_named_property` 4532 4533<!-- YAML 4534added: v8.0.0 4535napiVersion: 1 4536--> 4537 4538```c 4539napi_status napi_has_named_property(napi_env env, 4540 napi_value object, 4541 const char* utf8Name, 4542 bool* result); 4543``` 4544 4545* `[in] env`: The environment that the Node-API call is invoked under. 4546* `[in] object`: The object to query. 4547* `[in] utf8Name`: The name of the property whose existence to check. 4548* `[out] result`: Whether the property exists on the object or not. 4549 4550Returns `napi_ok` if the API succeeded. 4551 4552This method is equivalent to calling [`napi_has_property`][] with a `napi_value` 4553created from the string passed in as `utf8Name`. 4554 4555#### `napi_set_element` 4556 4557<!-- YAML 4558added: v8.0.0 4559napiVersion: 1 4560--> 4561 4562```c 4563napi_status napi_set_element(napi_env env, 4564 napi_value object, 4565 uint32_t index, 4566 napi_value value); 4567``` 4568 4569* `[in] env`: The environment that the Node-API call is invoked under. 4570* `[in] object`: The object from which to set the properties. 4571* `[in] index`: The index of the property to set. 4572* `[in] value`: The property value. 4573 4574Returns `napi_ok` if the API succeeded. 4575 4576This API sets an element on the `Object` passed in. 4577 4578#### `napi_get_element` 4579 4580<!-- YAML 4581added: v8.0.0 4582napiVersion: 1 4583--> 4584 4585```c 4586napi_status napi_get_element(napi_env env, 4587 napi_value object, 4588 uint32_t index, 4589 napi_value* result); 4590``` 4591 4592* `[in] env`: The environment that the Node-API call is invoked under. 4593* `[in] object`: The object from which to retrieve the property. 4594* `[in] index`: The index of the property to get. 4595* `[out] result`: The value of the property. 4596 4597Returns `napi_ok` if the API succeeded. 4598 4599This API gets the element at the requested index. 4600 4601#### `napi_has_element` 4602 4603<!-- YAML 4604added: v8.0.0 4605napiVersion: 1 4606--> 4607 4608```c 4609napi_status napi_has_element(napi_env env, 4610 napi_value object, 4611 uint32_t index, 4612 bool* result); 4613``` 4614 4615* `[in] env`: The environment that the Node-API call is invoked under. 4616* `[in] object`: The object to query. 4617* `[in] index`: The index of the property whose existence to check. 4618* `[out] result`: Whether the property exists on the object or not. 4619 4620Returns `napi_ok` if the API succeeded. 4621 4622This API returns if the `Object` passed in has an element at the 4623requested index. 4624 4625#### `napi_delete_element` 4626 4627<!-- YAML 4628added: v8.2.0 4629napiVersion: 1 4630--> 4631 4632```c 4633napi_status napi_delete_element(napi_env env, 4634 napi_value object, 4635 uint32_t index, 4636 bool* result); 4637``` 4638 4639* `[in] env`: The environment that the Node-API call is invoked under. 4640* `[in] object`: The object to query. 4641* `[in] index`: The index of the property to delete. 4642* `[out] result`: Whether the element deletion succeeded or not. `result` can 4643 optionally be ignored by passing `NULL`. 4644 4645Returns `napi_ok` if the API succeeded. 4646 4647This API attempts to delete the specified `index` from `object`. 4648 4649#### `napi_define_properties` 4650 4651<!-- YAML 4652added: v8.0.0 4653napiVersion: 1 4654--> 4655 4656```c 4657napi_status napi_define_properties(napi_env env, 4658 napi_value object, 4659 size_t property_count, 4660 const napi_property_descriptor* properties); 4661``` 4662 4663* `[in] env`: The environment that the Node-API call is invoked under. 4664* `[in] object`: The object from which to retrieve the properties. 4665* `[in] property_count`: The number of elements in the `properties` array. 4666* `[in] properties`: The array of property descriptors. 4667 4668Returns `napi_ok` if the API succeeded. 4669 4670This method allows the efficient definition of multiple properties on a given 4671object. The properties are defined using property descriptors (see 4672[`napi_property_descriptor`][]). Given an array of such property descriptors, 4673this API will set the properties on the object one at a time, as defined by 4674`DefineOwnProperty()` (described in [Section 9.1.6][] of the ECMA-262 4675specification). 4676 4677#### `napi_object_freeze` 4678 4679<!-- YAML 4680added: 4681 - v14.14.0 4682 - v12.20.0 4683napiVersion: 8 4684--> 4685 4686```c 4687napi_status napi_object_freeze(napi_env env, 4688 napi_value object); 4689``` 4690 4691* `[in] env`: The environment that the Node-API call is invoked under. 4692* `[in] object`: The object to freeze. 4693 4694Returns `napi_ok` if the API succeeded. 4695 4696This method freezes a given object. This prevents new properties from 4697being added to it, existing properties from being removed, prevents 4698changing the enumerability, configurability, or writability of existing 4699properties, and prevents the values of existing properties from being changed. 4700It also prevents the object's prototype from being changed. This is described 4701in [Section 19.1.2.6](https://tc39.es/ecma262/#sec-object.freeze) of the 4702ECMA-262 specification. 4703 4704#### `napi_object_seal` 4705 4706<!-- YAML 4707added: 4708 - v14.14.0 4709 - v12.20.0 4710napiVersion: 8 4711--> 4712 4713```c 4714napi_status napi_object_seal(napi_env env, 4715 napi_value object); 4716``` 4717 4718* `[in] env`: The environment that the Node-API call is invoked under. 4719* `[in] object`: The object to seal. 4720 4721Returns `napi_ok` if the API succeeded. 4722 4723This method seals a given object. This prevents new properties from being 4724added to it, as well as marking all existing properties as non-configurable. 4725This is described in [Section 19.1.2.20](https://tc39.es/ecma262/#sec-object.seal) 4726of the ECMA-262 specification. 4727 4728## Working with JavaScript functions 4729 4730Node-API provides a set of APIs that allow JavaScript code to 4731call back into native code. Node-APIs that support calling back 4732into native code take in a callback functions represented by 4733the `napi_callback` type. When the JavaScript VM calls back to 4734native code, the `napi_callback` function provided is invoked. The APIs 4735documented in this section allow the callback function to do the 4736following: 4737 4738* Get information about the context in which the callback was invoked. 4739* Get the arguments passed into the callback. 4740* Return a `napi_value` back from the callback. 4741 4742Additionally, Node-API provides a set of functions which allow calling 4743JavaScript functions from native code. One can either call a function 4744like a regular JavaScript function call, or as a constructor 4745function. 4746 4747Any non-`NULL` data which is passed to this API via the `data` field of the 4748`napi_property_descriptor` items can be associated with `object` and freed 4749whenever `object` is garbage-collected by passing both `object` and the data to 4750[`napi_add_finalizer`][]. 4751 4752### `napi_call_function` 4753 4754<!-- YAML 4755added: v8.0.0 4756napiVersion: 1 4757--> 4758 4759```c 4760NAPI_EXTERN napi_status napi_call_function(napi_env env, 4761 napi_value recv, 4762 napi_value func, 4763 size_t argc, 4764 const napi_value* argv, 4765 napi_value* result); 4766``` 4767 4768* `[in] env`: The environment that the API is invoked under. 4769* `[in] recv`: The `this` value passed to the called function. 4770* `[in] func`: `napi_value` representing the JavaScript function to be invoked. 4771* `[in] argc`: The count of elements in the `argv` array. 4772* `[in] argv`: Array of `napi_values` representing JavaScript values passed in 4773 as arguments to the function. 4774* `[out] result`: `napi_value` representing the JavaScript object returned. 4775 4776Returns `napi_ok` if the API succeeded. 4777 4778This method allows a JavaScript function object to be called from a native 4779add-on. This is the primary mechanism of calling back _from_ the add-on's 4780native code _into_ JavaScript. For the special case of calling into JavaScript 4781after an async operation, see [`napi_make_callback`][]. 4782 4783A sample use case might look as follows. Consider the following JavaScript 4784snippet: 4785 4786```js 4787function AddTwo(num) { 4788 return num + 2; 4789} 4790global.AddTwo = AddTwo; 4791``` 4792 4793Then, the above function can be invoked from a native add-on using the 4794following code: 4795 4796```c 4797// Get the function named "AddTwo" on the global object 4798napi_value global, add_two, arg; 4799napi_status status = napi_get_global(env, &global); 4800if (status != napi_ok) return; 4801 4802status = napi_get_named_property(env, global, "AddTwo", &add_two); 4803if (status != napi_ok) return; 4804 4805// const arg = 1337 4806status = napi_create_int32(env, 1337, &arg); 4807if (status != napi_ok) return; 4808 4809napi_value* argv = &arg; 4810size_t argc = 1; 4811 4812// AddTwo(arg); 4813napi_value return_val; 4814status = napi_call_function(env, global, add_two, argc, argv, &return_val); 4815if (status != napi_ok) return; 4816 4817// Convert the result back to a native type 4818int32_t result; 4819status = napi_get_value_int32(env, return_val, &result); 4820if (status != napi_ok) return; 4821``` 4822 4823### `napi_create_function` 4824 4825<!-- YAML 4826added: v8.0.0 4827napiVersion: 1 4828--> 4829 4830```c 4831napi_status napi_create_function(napi_env env, 4832 const char* utf8name, 4833 size_t length, 4834 napi_callback cb, 4835 void* data, 4836 napi_value* result); 4837``` 4838 4839* `[in] env`: The environment that the API is invoked under. 4840* `[in] utf8Name`: Optional name of the function encoded as UTF8. This is 4841 visible within JavaScript as the new function object's `name` property. 4842* `[in] length`: The length of the `utf8name` in bytes, or `NAPI_AUTO_LENGTH` if 4843 it is null-terminated. 4844* `[in] cb`: The native function which should be called when this function 4845 object is invoked. [`napi_callback`][] provides more details. 4846* `[in] data`: User-provided data context. This will be passed back into the 4847 function when invoked later. 4848* `[out] result`: `napi_value` representing the JavaScript function object for 4849 the newly created function. 4850 4851Returns `napi_ok` if the API succeeded. 4852 4853This API allows an add-on author to create a function object in native code. 4854This is the primary mechanism to allow calling _into_ the add-on's native code 4855_from_ JavaScript. 4856 4857The newly created function is not automatically visible from script after this 4858call. Instead, a property must be explicitly set on any object that is visible 4859to JavaScript, in order for the function to be accessible from script. 4860 4861In order to expose a function as part of the 4862add-on's module exports, set the newly created function on the exports 4863object. A sample module might look as follows: 4864 4865```c 4866napi_value SayHello(napi_env env, napi_callback_info info) { 4867 printf("Hello\n"); 4868 return NULL; 4869} 4870 4871napi_value Init(napi_env env, napi_value exports) { 4872 napi_status status; 4873 4874 napi_value fn; 4875 status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn); 4876 if (status != napi_ok) return NULL; 4877 4878 status = napi_set_named_property(env, exports, "sayHello", fn); 4879 if (status != napi_ok) return NULL; 4880 4881 return exports; 4882} 4883 4884NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) 4885``` 4886 4887Given the above code, the add-on can be used from JavaScript as follows: 4888 4889```js 4890const myaddon = require('./addon'); 4891myaddon.sayHello(); 4892``` 4893 4894The string passed to `require()` is the name of the target in `binding.gyp` 4895responsible for creating the `.node` file. 4896 4897Any non-`NULL` data which is passed to this API via the `data` parameter can 4898be associated with the resulting JavaScript function (which is returned in the 4899`result` parameter) and freed whenever the function is garbage-collected by 4900passing both the JavaScript function and the data to [`napi_add_finalizer`][]. 4901 4902JavaScript `Function`s are described in [Section 19.2][] of the ECMAScript 4903Language Specification. 4904 4905### `napi_get_cb_info` 4906 4907<!-- YAML 4908added: v8.0.0 4909napiVersion: 1 4910--> 4911 4912```c 4913napi_status napi_get_cb_info(napi_env env, 4914 napi_callback_info cbinfo, 4915 size_t* argc, 4916 napi_value* argv, 4917 napi_value* thisArg, 4918 void** data) 4919``` 4920 4921* `[in] env`: The environment that the API is invoked under. 4922* `[in] cbinfo`: The callback info passed into the callback function. 4923* `[in-out] argc`: Specifies the length of the provided `argv` array and 4924 receives the actual count of arguments. `argc` can 4925 optionally be ignored by passing `NULL`. 4926* `[out] argv`: C array of `napi_value`s to which the arguments will be 4927 copied. If there are more arguments than the provided count, only the 4928 requested number of arguments are copied. If there are fewer arguments 4929 provided than claimed, the rest of `argv` is filled with `napi_value` values 4930 that represent `undefined`. `argv` can optionally be ignored by 4931 passing `NULL`. 4932* `[out] thisArg`: Receives the JavaScript `this` argument for the call. 4933 `thisArg` can optionally be ignored by passing `NULL`. 4934* `[out] data`: Receives the data pointer for the callback. `data` can 4935 optionally be ignored by passing `NULL`. 4936 4937Returns `napi_ok` if the API succeeded. 4938 4939This method is used within a callback function to retrieve details about the 4940call like the arguments and the `this` pointer from a given callback info. 4941 4942### `napi_get_new_target` 4943 4944<!-- YAML 4945added: v8.6.0 4946napiVersion: 1 4947--> 4948 4949```c 4950napi_status napi_get_new_target(napi_env env, 4951 napi_callback_info cbinfo, 4952 napi_value* result) 4953``` 4954 4955* `[in] env`: The environment that the API is invoked under. 4956* `[in] cbinfo`: The callback info passed into the callback function. 4957* `[out] result`: The `new.target` of the constructor call. 4958 4959Returns `napi_ok` if the API succeeded. 4960 4961This API returns the `new.target` of the constructor call. If the current 4962callback is not a constructor call, the result is `NULL`. 4963 4964### `napi_new_instance` 4965 4966<!-- YAML 4967added: v8.0.0 4968napiVersion: 1 4969--> 4970 4971```c 4972napi_status napi_new_instance(napi_env env, 4973 napi_value cons, 4974 size_t argc, 4975 napi_value* argv, 4976 napi_value* result) 4977``` 4978 4979* `[in] env`: The environment that the API is invoked under. 4980* `[in] cons`: `napi_value` representing the JavaScript function to be invoked 4981 as a constructor. 4982* `[in] argc`: The count of elements in the `argv` array. 4983* `[in] argv`: Array of JavaScript values as `napi_value` representing the 4984 arguments to the constructor. If `argc` is zero this parameter may be 4985 omitted by passing in `NULL`. 4986* `[out] result`: `napi_value` representing the JavaScript object returned, 4987 which in this case is the constructed object. 4988 4989This method is used to instantiate a new JavaScript value using a given 4990`napi_value` that represents the constructor for the object. For example, 4991consider the following snippet: 4992 4993```js 4994function MyObject(param) { 4995 this.param = param; 4996} 4997 4998const arg = 'hello'; 4999const value = new MyObject(arg); 5000``` 5001 5002The following can be approximated in Node-API using the following snippet: 5003 5004```c 5005// Get the constructor function MyObject 5006napi_value global, constructor, arg, value; 5007napi_status status = napi_get_global(env, &global); 5008if (status != napi_ok) return; 5009 5010status = napi_get_named_property(env, global, "MyObject", &constructor); 5011if (status != napi_ok) return; 5012 5013// const arg = "hello" 5014status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &arg); 5015if (status != napi_ok) return; 5016 5017napi_value* argv = &arg; 5018size_t argc = 1; 5019 5020// const value = new MyObject(arg) 5021status = napi_new_instance(env, constructor, argc, argv, &value); 5022``` 5023 5024Returns `napi_ok` if the API succeeded. 5025 5026## Object wrap 5027 5028Node-API offers a way to "wrap" C++ classes and instances so that the class 5029constructor and methods can be called from JavaScript. 5030 50311. The [`napi_define_class`][] API defines a JavaScript class with constructor, 5032 static properties and methods, and instance properties and methods that 5033 correspond to the C++ class. 50342. When JavaScript code invokes the constructor, the constructor callback 5035 uses [`napi_wrap`][] to wrap a new C++ instance in a JavaScript object, 5036 then returns the wrapper object. 50373. When JavaScript code invokes a method or property accessor on the class, 5038 the corresponding `napi_callback` C++ function is invoked. For an instance 5039 callback, [`napi_unwrap`][] obtains the C++ instance that is the target of 5040 the call. 5041 5042For wrapped objects it may be difficult to distinguish between a function 5043called on a class prototype and a function called on an instance of a class. 5044A common pattern used to address this problem is to save a persistent 5045reference to the class constructor for later `instanceof` checks. 5046 5047```c 5048napi_value MyClass_constructor = NULL; 5049status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor); 5050assert(napi_ok == status); 5051bool is_instance = false; 5052status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance); 5053assert(napi_ok == status); 5054if (is_instance) { 5055 // napi_unwrap() ... 5056} else { 5057 // otherwise... 5058} 5059``` 5060 5061The reference must be freed once it is no longer needed. 5062 5063There are occasions where `napi_instanceof()` is insufficient for ensuring that 5064a JavaScript object is a wrapper for a certain native type. This is the case 5065especially when wrapped JavaScript objects are passed back into the addon via 5066static methods rather than as the `this` value of prototype methods. In such 5067cases there is a chance that they may be unwrapped incorrectly. 5068 5069```js 5070const myAddon = require('./build/Release/my_addon.node'); 5071 5072// `openDatabase()` returns a JavaScript object that wraps a native database 5073// handle. 5074const dbHandle = myAddon.openDatabase(); 5075 5076// `query()` returns a JavaScript object that wraps a native query handle. 5077const queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!'); 5078 5079// There is an accidental error in the line below. The first parameter to 5080// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not 5081// the query handle (`query`), so the correct condition for the while-loop 5082// should be 5083// 5084// myAddon.queryHasRecords(dbHandle, queryHandle) 5085// 5086while (myAddon.queryHasRecords(queryHandle, dbHandle)) { 5087 // retrieve records 5088} 5089``` 5090 5091In the above example `myAddon.queryHasRecords()` is a method that accepts two 5092arguments. The first is a database handle and the second is a query handle. 5093Internally, it unwraps the first argument and casts the resulting pointer to a 5094native database handle. It then unwraps the second argument and casts the 5095resulting pointer to a query handle. If the arguments are passed in the wrong 5096order, the casts will work, however, there is a good chance that the underlying 5097database operation will fail, or will even cause an invalid memory access. 5098 5099To ensure that the pointer retrieved from the first argument is indeed a pointer 5100to a database handle and, similarly, that the pointer retrieved from the second 5101argument is indeed a pointer to a query handle, the implementation of 5102`queryHasRecords()` has to perform a type validation. Retaining the JavaScript 5103class constructor from which the database handle was instantiated and the 5104constructor from which the query handle was instantiated in `napi_ref`s can 5105help, because `napi_instanceof()` can then be used to ensure that the instances 5106passed into `queryHashRecords()` are indeed of the correct type. 5107 5108Unfortunately, `napi_instanceof()` does not protect against prototype 5109manipulation. For example, the prototype of the database handle instance can be 5110set to the prototype of the constructor for query handle instances. In this 5111case, the database handle instance can appear as a query handle instance, and it 5112will pass the `napi_instanceof()` test for a query handle instance, while still 5113containing a pointer to a database handle. 5114 5115To this end, Node-API provides type-tagging capabilities. 5116 5117A type tag is a 128-bit integer unique to the addon. Node-API provides the 5118`napi_type_tag` structure for storing a type tag. When such a value is passed 5119along with a JavaScript object or [external][] stored in a `napi_value` to 5120`napi_type_tag_object()`, the JavaScript object will be "marked" with the 5121type tag. The "mark" is invisible on the JavaScript side. When a JavaScript 5122object arrives into a native binding, `napi_check_object_type_tag()` can be used 5123along with the original type tag to determine whether the JavaScript object was 5124previously "marked" with the type tag. This creates a type-checking capability 5125of a higher fidelity than `napi_instanceof()` can provide, because such type- 5126tagging survives prototype manipulation and addon unloading/reloading. 5127 5128Continuing the above example, the following skeleton addon implementation 5129illustrates the use of `napi_type_tag_object()` and 5130`napi_check_object_type_tag()`. 5131 5132```c 5133// This value is the type tag for a database handle. The command 5134// 5135// uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/' 5136// 5137// can be used to obtain the two values with which to initialize the structure. 5138static const napi_type_tag DatabaseHandleTypeTag = { 5139 0x1edf75a38336451d, 0xa5ed9ce2e4c00c38 5140}; 5141 5142// This value is the type tag for a query handle. 5143static const napi_type_tag QueryHandleTypeTag = { 5144 0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a 5145}; 5146 5147static napi_value 5148openDatabase(napi_env env, napi_callback_info info) { 5149 napi_status status; 5150 napi_value result; 5151 5152 // Perform the underlying action which results in a database handle. 5153 DatabaseHandle* dbHandle = open_database(); 5154 5155 // Create a new, empty JS object. 5156 status = napi_create_object(env, &result); 5157 if (status != napi_ok) return NULL; 5158 5159 // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`. 5160 status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag); 5161 if (status != napi_ok) return NULL; 5162 5163 // Store the pointer to the `DatabaseHandle` structure inside the JS object. 5164 status = napi_wrap(env, result, dbHandle, NULL, NULL, NULL); 5165 if (status != napi_ok) return NULL; 5166 5167 return result; 5168} 5169 5170// Later when we receive a JavaScript object purporting to be a database handle 5171// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a 5172// handle. 5173 5174static napi_value 5175query(napi_env env, napi_callback_info info) { 5176 napi_status status; 5177 size_t argc = 2; 5178 napi_value argv[2]; 5179 bool is_db_handle; 5180 5181 status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); 5182 if (status != napi_ok) return NULL; 5183 5184 // Check that the object passed as the first parameter has the previously 5185 // applied tag. 5186 status = napi_check_object_type_tag(env, 5187 argv[0], 5188 &DatabaseHandleTypeTag, 5189 &is_db_handle); 5190 if (status != napi_ok) return NULL; 5191 5192 // Throw a `TypeError` if it doesn't. 5193 if (!is_db_handle) { 5194 // Throw a TypeError. 5195 return NULL; 5196 } 5197} 5198``` 5199 5200### `napi_define_class` 5201 5202<!-- YAML 5203added: v8.0.0 5204napiVersion: 1 5205--> 5206 5207```c 5208napi_status napi_define_class(napi_env env, 5209 const char* utf8name, 5210 size_t length, 5211 napi_callback constructor, 5212 void* data, 5213 size_t property_count, 5214 const napi_property_descriptor* properties, 5215 napi_value* result); 5216``` 5217 5218* `[in] env`: The environment that the API is invoked under. 5219* `[in] utf8name`: Name of the JavaScript constructor function. For clarity, 5220 it is recommended to use the C++ class name when wrapping a C++ class. 5221* `[in] length`: The length of the `utf8name` in bytes, or `NAPI_AUTO_LENGTH` 5222 if it is null-terminated. 5223* `[in] constructor`: Callback function that handles constructing instances 5224 of the class. When wrapping a C++ class, this method must be a static member 5225 with the [`napi_callback`][] signature. A C++ class constructor cannot be 5226 used. [`napi_callback`][] provides more details. 5227* `[in] data`: Optional data to be passed to the constructor callback as 5228 the `data` property of the callback info. 5229* `[in] property_count`: Number of items in the `properties` array argument. 5230* `[in] properties`: Array of property descriptors describing static and 5231 instance data properties, accessors, and methods on the class 5232 See `napi_property_descriptor`. 5233* `[out] result`: A `napi_value` representing the constructor function for 5234 the class. 5235 5236Returns `napi_ok` if the API succeeded. 5237 5238Defines a JavaScript class, including: 5239 5240* A JavaScript constructor function that has the class name. When wrapping a 5241 corresponding C++ class, the callback passed via `constructor` can be used to 5242 instantiate a new C++ class instance, which can then be placed inside the 5243 JavaScript object instance being constructed using [`napi_wrap`][]. 5244* Properties on the constructor function whose implementation can call 5245 corresponding _static_ data properties, accessors, and methods of the C++ 5246 class (defined by property descriptors with the `napi_static` attribute). 5247* Properties on the constructor function's `prototype` object. When wrapping a 5248 C++ class, _non-static_ data properties, accessors, and methods of the C++ 5249 class can be called from the static functions given in the property 5250 descriptors without the `napi_static` attribute after retrieving the C++ class 5251 instance placed inside the JavaScript object instance by using 5252 [`napi_unwrap`][]. 5253 5254When wrapping a C++ class, the C++ constructor callback passed via `constructor` 5255should be a static method on the class that calls the actual class constructor, 5256then wraps the new C++ instance in a JavaScript object, and returns the wrapper 5257object. See [`napi_wrap`][] for details. 5258 5259The JavaScript constructor function returned from [`napi_define_class`][] is 5260often saved and used later to construct new instances of the class from native 5261code, and/or to check whether provided values are instances of the class. In 5262that case, to prevent the function value from being garbage-collected, a 5263strong persistent reference to it can be created using 5264[`napi_create_reference`][], ensuring that the reference count is kept >= 1. 5265 5266Any non-`NULL` data which is passed to this API via the `data` parameter or via 5267the `data` field of the `napi_property_descriptor` array items can be associated 5268with the resulting JavaScript constructor (which is returned in the `result` 5269parameter) and freed whenever the class is garbage-collected by passing both 5270the JavaScript function and the data to [`napi_add_finalizer`][]. 5271 5272### `napi_wrap` 5273 5274<!-- YAML 5275added: v8.0.0 5276napiVersion: 1 5277--> 5278 5279```c 5280napi_status napi_wrap(napi_env env, 5281 napi_value js_object, 5282 void* native_object, 5283 napi_finalize finalize_cb, 5284 void* finalize_hint, 5285 napi_ref* result); 5286``` 5287 5288* `[in] env`: The environment that the API is invoked under. 5289* `[in] js_object`: The JavaScript object that will be the wrapper for the 5290 native object. 5291* `[in] native_object`: The native instance that will be wrapped in the 5292 JavaScript object. 5293* `[in] finalize_cb`: Optional native callback that can be used to free the 5294 native instance when the JavaScript object has been garbage-collected. 5295 [`napi_finalize`][] provides more details. 5296* `[in] finalize_hint`: Optional contextual hint that is passed to the 5297 finalize callback. 5298* `[out] result`: Optional reference to the wrapped object. 5299 5300Returns `napi_ok` if the API succeeded. 5301 5302Wraps a native instance in a JavaScript object. The native instance can be 5303retrieved later using `napi_unwrap()`. 5304 5305When JavaScript code invokes a constructor for a class that was defined using 5306`napi_define_class()`, the `napi_callback` for the constructor is invoked. 5307After constructing an instance of the native class, the callback must then call 5308`napi_wrap()` to wrap the newly constructed instance in the already-created 5309JavaScript object that is the `this` argument to the constructor callback. 5310(That `this` object was created from the constructor function's `prototype`, 5311so it already has definitions of all the instance properties and methods.) 5312 5313Typically when wrapping a class instance, a finalize callback should be 5314provided that simply deletes the native instance that is received as the `data` 5315argument to the finalize callback. 5316 5317The optional returned reference is initially a weak reference, meaning it 5318has a reference count of 0. Typically this reference count would be incremented 5319temporarily during async operations that require the instance to remain valid. 5320 5321_Caution_: The optional returned reference (if obtained) should be deleted via 5322[`napi_delete_reference`][] ONLY in response to the finalize callback 5323invocation. If it is deleted before then, then the finalize callback may never 5324be invoked. Therefore, when obtaining a reference a finalize callback is also 5325required in order to enable correct disposal of the reference. 5326 5327Finalizer callbacks may be deferred, leaving a window where the object has 5328been garbage collected (and the weak reference is invalid) but the finalizer 5329hasn't been called yet. When using `napi_get_reference_value()` on weak 5330references returned by `napi_wrap()`, you should still handle an empty result. 5331 5332Calling `napi_wrap()` a second time on an object will return an error. To 5333associate another native instance with the object, use `napi_remove_wrap()` 5334first. 5335 5336### `napi_unwrap` 5337 5338<!-- YAML 5339added: v8.0.0 5340napiVersion: 1 5341--> 5342 5343```c 5344napi_status napi_unwrap(napi_env env, 5345 napi_value js_object, 5346 void** result); 5347``` 5348 5349* `[in] env`: The environment that the API is invoked under. 5350* `[in] js_object`: The object associated with the native instance. 5351* `[out] result`: Pointer to the wrapped native instance. 5352 5353Returns `napi_ok` if the API succeeded. 5354 5355Retrieves a native instance that was previously wrapped in a JavaScript 5356object using `napi_wrap()`. 5357 5358When JavaScript code invokes a method or property accessor on the class, the 5359corresponding `napi_callback` is invoked. If the callback is for an instance 5360method or accessor, then the `this` argument to the callback is the wrapper 5361object; the wrapped C++ instance that is the target of the call can be obtained 5362then by calling `napi_unwrap()` on the wrapper object. 5363 5364### `napi_remove_wrap` 5365 5366<!-- YAML 5367added: v8.5.0 5368napiVersion: 1 5369--> 5370 5371```c 5372napi_status napi_remove_wrap(napi_env env, 5373 napi_value js_object, 5374 void** result); 5375``` 5376 5377* `[in] env`: The environment that the API is invoked under. 5378* `[in] js_object`: The object associated with the native instance. 5379* `[out] result`: Pointer to the wrapped native instance. 5380 5381Returns `napi_ok` if the API succeeded. 5382 5383Retrieves a native instance that was previously wrapped in the JavaScript 5384object `js_object` using `napi_wrap()` and removes the wrapping. If a finalize 5385callback was associated with the wrapping, it will no longer be called when the 5386JavaScript object becomes garbage-collected. 5387 5388### `napi_type_tag_object` 5389 5390<!-- YAML 5391added: 5392 - v14.8.0 5393 - v12.19.0 5394napiVersion: 8 5395--> 5396 5397```c 5398napi_status napi_type_tag_object(napi_env env, 5399 napi_value js_object, 5400 const napi_type_tag* type_tag); 5401``` 5402 5403* `[in] env`: The environment that the API is invoked under. 5404* `[in] js_object`: The JavaScript object or [external][] to be marked. 5405* `[in] type_tag`: The tag with which the object is to be marked. 5406 5407Returns `napi_ok` if the API succeeded. 5408 5409Associates the value of the `type_tag` pointer with the JavaScript object or 5410[external][]. `napi_check_object_type_tag()` can then be used to compare the tag 5411that was attached to the object with one owned by the addon to ensure that the 5412object has the right type. 5413 5414If the object already has an associated type tag, this API will return 5415`napi_invalid_arg`. 5416 5417### `napi_check_object_type_tag` 5418 5419<!-- YAML 5420added: 5421 - v14.8.0 5422 - v12.19.0 5423napiVersion: 8 5424--> 5425 5426```c 5427napi_status napi_check_object_type_tag(napi_env env, 5428 napi_value js_object, 5429 const napi_type_tag* type_tag, 5430 bool* result); 5431``` 5432 5433* `[in] env`: The environment that the API is invoked under. 5434* `[in] js_object`: The JavaScript object or [external][] whose type tag to 5435 examine. 5436* `[in] type_tag`: The tag with which to compare any tag found on the object. 5437* `[out] result`: Whether the type tag given matched the type tag on the 5438 object. `false` is also returned if no type tag was found on the object. 5439 5440Returns `napi_ok` if the API succeeded. 5441 5442Compares the pointer given as `type_tag` with any that can be found on 5443`js_object`. If no tag is found on `js_object` or, if a tag is found but it does 5444not match `type_tag`, then `result` is set to `false`. If a tag is found and it 5445matches `type_tag`, then `result` is set to `true`. 5446 5447### `napi_add_finalizer` 5448 5449<!-- YAML 5450added: v8.0.0 5451napiVersion: 5 5452--> 5453 5454```c 5455napi_status napi_add_finalizer(napi_env env, 5456 napi_value js_object, 5457 void* finalize_data, 5458 node_api_nogc_finalize finalize_cb, 5459 void* finalize_hint, 5460 napi_ref* result); 5461``` 5462 5463* `[in] env`: The environment that the API is invoked under. 5464* `[in] js_object`: The JavaScript object to which the native data will be 5465 attached. 5466* `[in] finalize_data`: Optional data to be passed to `finalize_cb`. 5467* `[in] finalize_cb`: Native callback that will be used to free the 5468 native data when the JavaScript object has been garbage-collected. 5469 [`napi_finalize`][] provides more details. 5470* `[in] finalize_hint`: Optional contextual hint that is passed to the 5471 finalize callback. 5472* `[out] result`: Optional reference to the JavaScript object. 5473 5474Returns `napi_ok` if the API succeeded. 5475 5476Adds a `napi_finalize` callback which will be called when the JavaScript object 5477in `js_object` has been garbage-collected. 5478 5479This API can be called multiple times on a single JavaScript object. 5480 5481_Caution_: The optional returned reference (if obtained) should be deleted via 5482[`napi_delete_reference`][] ONLY in response to the finalize callback 5483invocation. If it is deleted before then, then the finalize callback may never 5484be invoked. Therefore, when obtaining a reference a finalize callback is also 5485required in order to enable correct disposal of the reference. 5486 5487#### `node_api_post_finalizer` 5488 5489<!-- YAML 5490added: v18.19.0 5491--> 5492 5493> Stability: 1 - Experimental 5494 5495```c 5496napi_status node_api_post_finalizer(node_api_nogc_env env, 5497 napi_finalize finalize_cb, 5498 void* finalize_data, 5499 void* finalize_hint); 5500``` 5501 5502* `[in] env`: The environment that the API is invoked under. 5503* `[in] finalize_cb`: Native callback that will be used to free the 5504 native data when the JavaScript object has been garbage-collected. 5505 [`napi_finalize`][] provides more details. 5506* `[in] finalize_data`: Optional data to be passed to `finalize_cb`. 5507* `[in] finalize_hint`: Optional contextual hint that is passed to the 5508 finalize callback. 5509 5510Returns `napi_ok` if the API succeeded. 5511 5512Schedules a `napi_finalize` callback to be called asynchronously in the 5513event loop. 5514 5515Normally, finalizers are called while the GC (garbage collector) collects 5516objects. At that point calling any Node-API that may cause changes in the GC 5517state will be disabled and will crash Node.js. 5518 5519`node_api_post_finalizer` helps to work around this limitation by allowing the 5520add-on to defer calls to such Node-APIs to a point in time outside of the GC 5521finalization. 5522 5523## Simple asynchronous operations 5524 5525Addon modules often need to leverage async helpers from libuv as part of their 5526implementation. This allows them to schedule work to be executed asynchronously 5527so that their methods can return in advance of the work being completed. This 5528allows them to avoid blocking overall execution of the Node.js application. 5529 5530Node-API provides an ABI-stable interface for these 5531supporting functions which covers the most common asynchronous use cases. 5532 5533Node-API defines the `napi_async_work` structure which is used to manage 5534asynchronous workers. Instances are created/deleted with 5535[`napi_create_async_work`][] and [`napi_delete_async_work`][]. 5536 5537The `execute` and `complete` callbacks are functions that will be 5538invoked when the executor is ready to execute and when it completes its 5539task respectively. 5540 5541The `execute` function should avoid making any Node-API calls 5542that could result in the execution of JavaScript or interaction with 5543JavaScript objects. Most often, any code that needs to make Node-API 5544calls should be made in `complete` callback instead. 5545Avoid using the `napi_env` parameter in the execute callback as 5546it will likely execute JavaScript. 5547 5548These functions implement the following interfaces: 5549 5550```c 5551typedef void (*napi_async_execute_callback)(napi_env env, 5552 void* data); 5553typedef void (*napi_async_complete_callback)(napi_env env, 5554 napi_status status, 5555 void* data); 5556``` 5557 5558When these methods are invoked, the `data` parameter passed will be the 5559addon-provided `void*` data that was passed into the 5560`napi_create_async_work` call. 5561 5562Once created the async worker can be queued 5563for execution using the [`napi_queue_async_work`][] function: 5564 5565```c 5566napi_status napi_queue_async_work(node_api_nogc_env env, 5567 napi_async_work work); 5568``` 5569 5570[`napi_cancel_async_work`][] can be used if the work needs 5571to be cancelled before the work has started execution. 5572 5573After calling [`napi_cancel_async_work`][], the `complete` callback 5574will be invoked with a status value of `napi_cancelled`. 5575The work should not be deleted before the `complete` 5576callback invocation, even when it was cancelled. 5577 5578### `napi_create_async_work` 5579 5580<!-- YAML 5581added: v8.0.0 5582napiVersion: 1 5583changes: 5584 - version: v8.6.0 5585 pr-url: https://github.com/nodejs/node/pull/14697 5586 description: Added `async_resource` and `async_resource_name` parameters. 5587--> 5588 5589```c 5590napi_status napi_create_async_work(napi_env env, 5591 napi_value async_resource, 5592 napi_value async_resource_name, 5593 napi_async_execute_callback execute, 5594 napi_async_complete_callback complete, 5595 void* data, 5596 napi_async_work* result); 5597``` 5598 5599* `[in] env`: The environment that the API is invoked under. 5600* `[in] async_resource`: An optional object associated with the async work 5601 that will be passed to possible `async_hooks` [`init` hooks][]. 5602* `[in] async_resource_name`: Identifier for the kind of resource that is being 5603 provided for diagnostic information exposed by the `async_hooks` API. 5604* `[in] execute`: The native function which should be called to execute the 5605 logic asynchronously. The given function is called from a worker pool thread 5606 and can execute in parallel with the main event loop thread. 5607* `[in] complete`: The native function which will be called when the 5608 asynchronous logic is completed or is cancelled. The given function is called 5609 from the main event loop thread. [`napi_async_complete_callback`][] provides 5610 more details. 5611* `[in] data`: User-provided data context. This will be passed back into the 5612 execute and complete functions. 5613* `[out] result`: `napi_async_work*` which is the handle to the newly created 5614 async work. 5615 5616Returns `napi_ok` if the API succeeded. 5617 5618This API allocates a work object that is used to execute logic asynchronously. 5619It should be freed using [`napi_delete_async_work`][] once the work is no longer 5620required. 5621 5622`async_resource_name` should be a null-terminated, UTF-8-encoded string. 5623 5624The `async_resource_name` identifier is provided by the user and should be 5625representative of the type of async work being performed. It is also recommended 5626to apply namespacing to the identifier, e.g. by including the module name. See 5627the [`async_hooks` documentation][async_hooks `type`] for more information. 5628 5629### `napi_delete_async_work` 5630 5631<!-- YAML 5632added: v8.0.0 5633napiVersion: 1 5634--> 5635 5636```c 5637napi_status napi_delete_async_work(napi_env env, 5638 napi_async_work work); 5639``` 5640 5641* `[in] env`: The environment that the API is invoked under. 5642* `[in] work`: The handle returned by the call to `napi_create_async_work`. 5643 5644Returns `napi_ok` if the API succeeded. 5645 5646This API frees a previously allocated work object. 5647 5648This API can be called even if there is a pending JavaScript exception. 5649 5650### `napi_queue_async_work` 5651 5652<!-- YAML 5653added: v8.0.0 5654napiVersion: 1 5655--> 5656 5657```c 5658napi_status napi_queue_async_work(node_api_nogc_env env, 5659 napi_async_work work); 5660``` 5661 5662* `[in] env`: The environment that the API is invoked under. 5663* `[in] work`: The handle returned by the call to `napi_create_async_work`. 5664 5665Returns `napi_ok` if the API succeeded. 5666 5667This API requests that the previously allocated work be scheduled 5668for execution. Once it returns successfully, this API must not be called again 5669with the same `napi_async_work` item or the result will be undefined. 5670 5671### `napi_cancel_async_work` 5672 5673<!-- YAML 5674added: v8.0.0 5675napiVersion: 1 5676--> 5677 5678```c 5679napi_status napi_cancel_async_work(node_api_nogc_env env, 5680 napi_async_work work); 5681``` 5682 5683* `[in] env`: The environment that the API is invoked under. 5684* `[in] work`: The handle returned by the call to `napi_create_async_work`. 5685 5686Returns `napi_ok` if the API succeeded. 5687 5688This API cancels queued work if it has not yet 5689been started. If it has already started executing, it cannot be 5690cancelled and `napi_generic_failure` will be returned. If successful, 5691the `complete` callback will be invoked with a status value of 5692`napi_cancelled`. The work should not be deleted before the `complete` 5693callback invocation, even if it has been successfully cancelled. 5694 5695This API can be called even if there is a pending JavaScript exception. 5696 5697## Custom asynchronous operations 5698 5699The simple asynchronous work APIs above may not be appropriate for every 5700scenario. When using any other asynchronous mechanism, the following APIs 5701are necessary to ensure an asynchronous operation is properly tracked by 5702the runtime. 5703 5704### `napi_async_init` 5705 5706<!-- YAML 5707added: v8.6.0 5708napiVersion: 1 5709--> 5710 5711```c 5712napi_status napi_async_init(napi_env env, 5713 napi_value async_resource, 5714 napi_value async_resource_name, 5715 napi_async_context* result) 5716``` 5717 5718* `[in] env`: The environment that the API is invoked under. 5719* `[in] async_resource`: Object associated with the async work 5720 that will be passed to possible `async_hooks` [`init` hooks][] and can be 5721 accessed by [`async_hooks.executionAsyncResource()`][]. 5722* `[in] async_resource_name`: Identifier for the kind of resource that is being 5723 provided for diagnostic information exposed by the `async_hooks` API. 5724* `[out] result`: The initialized async context. 5725 5726Returns `napi_ok` if the API succeeded. 5727 5728The `async_resource` object needs to be kept alive until 5729[`napi_async_destroy`][] to keep `async_hooks` related API acts correctly. In 5730order to retain ABI compatibility with previous versions, `napi_async_context`s 5731are not maintaining the strong reference to the `async_resource` objects to 5732avoid introducing causing memory leaks. However, if the `async_resource` is 5733garbage collected by JavaScript engine before the `napi_async_context` was 5734destroyed by `napi_async_destroy`, calling `napi_async_context` related APIs 5735like [`napi_open_callback_scope`][] and [`napi_make_callback`][] can cause 5736problems like loss of async context when using the `AsyncLocalStorage` API. 5737 5738In order to retain ABI compatibility with previous versions, passing `NULL` 5739for `async_resource` does not result in an error. However, this is not 5740recommended as this will result in undesirable behavior with `async_hooks` 5741[`init` hooks][] and `async_hooks.executionAsyncResource()` as the resource is 5742now required by the underlying `async_hooks` implementation in order to provide 5743the linkage between async callbacks. 5744 5745### `napi_async_destroy` 5746 5747<!-- YAML 5748added: v8.6.0 5749napiVersion: 1 5750--> 5751 5752```c 5753napi_status napi_async_destroy(napi_env env, 5754 napi_async_context async_context); 5755``` 5756 5757* `[in] env`: The environment that the API is invoked under. 5758* `[in] async_context`: The async context to be destroyed. 5759 5760Returns `napi_ok` if the API succeeded. 5761 5762This API can be called even if there is a pending JavaScript exception. 5763 5764### `napi_make_callback` 5765 5766<!-- YAML 5767added: v8.0.0 5768napiVersion: 1 5769changes: 5770 - version: v8.6.0 5771 pr-url: https://github.com/nodejs/node/pull/15189 5772 description: Added `async_context` parameter. 5773--> 5774 5775```c 5776NAPI_EXTERN napi_status napi_make_callback(napi_env env, 5777 napi_async_context async_context, 5778 napi_value recv, 5779 napi_value func, 5780 size_t argc, 5781 const napi_value* argv, 5782 napi_value* result); 5783``` 5784 5785* `[in] env`: The environment that the API is invoked under. 5786* `[in] async_context`: Context for the async operation that is 5787 invoking the callback. This should normally be a value previously 5788 obtained from [`napi_async_init`][]. 5789 In order to retain ABI compatibility with previous versions, passing `NULL` 5790 for `async_context` does not result in an error. However, this results 5791 in incorrect operation of async hooks. Potential issues include loss of 5792 async context when using the `AsyncLocalStorage` API. 5793* `[in] recv`: The `this` value passed to the called function. 5794* `[in] func`: `napi_value` representing the JavaScript function to be invoked. 5795* `[in] argc`: The count of elements in the `argv` array. 5796* `[in] argv`: Array of JavaScript values as `napi_value` representing the 5797 arguments to the function. If `argc` is zero this parameter may be 5798 omitted by passing in `NULL`. 5799* `[out] result`: `napi_value` representing the JavaScript object returned. 5800 5801Returns `napi_ok` if the API succeeded. 5802 5803This method allows a JavaScript function object to be called from a native 5804add-on. This API is similar to `napi_call_function`. However, it is used to call 5805_from_ native code back _into_ JavaScript _after_ returning from an async 5806operation (when there is no other script on the stack). It is a fairly simple 5807wrapper around `node::MakeCallback`. 5808 5809Note it is _not_ necessary to use `napi_make_callback` from within a 5810`napi_async_complete_callback`; in that situation the callback's async 5811context has already been set up, so a direct call to `napi_call_function` 5812is sufficient and appropriate. Use of the `napi_make_callback` function 5813may be required when implementing custom async behavior that does not use 5814`napi_create_async_work`. 5815 5816Any `process.nextTick`s or Promises scheduled on the microtask queue by 5817JavaScript during the callback are ran before returning back to C/C++. 5818 5819### `napi_open_callback_scope` 5820 5821<!-- YAML 5822added: v9.6.0 5823napiVersion: 3 5824--> 5825 5826```c 5827NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env, 5828 napi_value resource_object, 5829 napi_async_context context, 5830 napi_callback_scope* result) 5831``` 5832 5833* `[in] env`: The environment that the API is invoked under. 5834* `[in] resource_object`: An object associated with the async work 5835 that will be passed to possible `async_hooks` [`init` hooks][]. This 5836 parameter has been deprecated and is ignored at runtime. Use the 5837 `async_resource` parameter in [`napi_async_init`][] instead. 5838* `[in] context`: Context for the async operation that is invoking the callback. 5839 This should be a value previously obtained from [`napi_async_init`][]. 5840* `[out] result`: The newly created scope. 5841 5842There are cases (for example, resolving promises) where it is 5843necessary to have the equivalent of the scope associated with a callback 5844in place when making certain Node-API calls. If there is no other script on 5845the stack the [`napi_open_callback_scope`][] and 5846[`napi_close_callback_scope`][] functions can be used to open/close 5847the required scope. 5848 5849### `napi_close_callback_scope` 5850 5851<!-- YAML 5852added: v9.6.0 5853napiVersion: 3 5854--> 5855 5856```c 5857NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env, 5858 napi_callback_scope scope) 5859``` 5860 5861* `[in] env`: The environment that the API is invoked under. 5862* `[in] scope`: The scope to be closed. 5863 5864This API can be called even if there is a pending JavaScript exception. 5865 5866## Version management 5867 5868### `napi_get_node_version` 5869 5870<!-- YAML 5871added: v8.4.0 5872napiVersion: 1 5873--> 5874 5875```c 5876typedef struct { 5877 uint32_t major; 5878 uint32_t minor; 5879 uint32_t patch; 5880 const char* release; 5881} napi_node_version; 5882 5883napi_status napi_get_node_version(node_api_nogc_env env, 5884 const napi_node_version** version); 5885``` 5886 5887* `[in] env`: The environment that the API is invoked under. 5888* `[out] version`: A pointer to version information for Node.js itself. 5889 5890Returns `napi_ok` if the API succeeded. 5891 5892This function fills the `version` struct with the major, minor, and patch 5893version of Node.js that is currently running, and the `release` field with the 5894value of [`process.release.name`][`process.release`]. 5895 5896The returned buffer is statically allocated and does not need to be freed. 5897 5898### `napi_get_version` 5899 5900<!-- YAML 5901added: v8.0.0 5902napiVersion: 1 5903--> 5904 5905```c 5906napi_status napi_get_version(node_api_nogc_env env, 5907 uint32_t* result); 5908``` 5909 5910* `[in] env`: The environment that the API is invoked under. 5911* `[out] result`: The highest version of Node-API supported. 5912 5913Returns `napi_ok` if the API succeeded. 5914 5915This API returns the highest Node-API version supported by the 5916Node.js runtime. Node-API is planned to be additive such that 5917newer releases of Node.js may support additional API functions. 5918In order to allow an addon to use a newer function when running with 5919versions of Node.js that support it, while providing 5920fallback behavior when running with Node.js versions that don't 5921support it: 5922 5923* Call `napi_get_version()` to determine if the API is available. 5924* If available, dynamically load a pointer to the function using `uv_dlsym()`. 5925* Use the dynamically loaded pointer to invoke the function. 5926* If the function is not available, provide an alternate implementation 5927 that does not use the function. 5928 5929## Memory management 5930 5931### `napi_adjust_external_memory` 5932 5933<!-- YAML 5934added: v8.5.0 5935napiVersion: 1 5936--> 5937 5938```c 5939NAPI_EXTERN napi_status napi_adjust_external_memory(node_api_nogc_env env, 5940 int64_t change_in_bytes, 5941 int64_t* result); 5942``` 5943 5944* `[in] env`: The environment that the API is invoked under. 5945* `[in] change_in_bytes`: The change in externally allocated memory that is kept 5946 alive by JavaScript objects. 5947* `[out] result`: The adjusted value 5948 5949Returns `napi_ok` if the API succeeded. 5950 5951This function gives V8 an indication of the amount of externally allocated 5952memory that is kept alive by JavaScript objects (i.e. a JavaScript object 5953that points to its own memory allocated by a native addon). Registering 5954externally allocated memory will trigger global garbage collections more 5955often than it would otherwise. 5956 5957## Promises 5958 5959Node-API provides facilities for creating `Promise` objects as described in 5960[Section 25.4][] of the ECMA specification. It implements promises as a pair of 5961objects. When a promise is created by `napi_create_promise()`, a "deferred" 5962object is created and returned alongside the `Promise`. The deferred object is 5963bound to the created `Promise` and is the only means to resolve or reject the 5964`Promise` using `napi_resolve_deferred()` or `napi_reject_deferred()`. The 5965deferred object that is created by `napi_create_promise()` is freed by 5966`napi_resolve_deferred()` or `napi_reject_deferred()`. The `Promise` object may 5967be returned to JavaScript where it can be used in the usual fashion. 5968 5969For example, to create a promise and pass it to an asynchronous worker: 5970 5971```c 5972napi_deferred deferred; 5973napi_value promise; 5974napi_status status; 5975 5976// Create the promise. 5977status = napi_create_promise(env, &deferred, &promise); 5978if (status != napi_ok) return NULL; 5979 5980// Pass the deferred to a function that performs an asynchronous action. 5981do_something_asynchronous(deferred); 5982 5983// Return the promise to JS 5984return promise; 5985``` 5986 5987The above function `do_something_asynchronous()` would perform its asynchronous 5988action and then it would resolve or reject the deferred, thereby concluding the 5989promise and freeing the deferred: 5990 5991```c 5992napi_deferred deferred; 5993napi_value undefined; 5994napi_status status; 5995 5996// Create a value with which to conclude the deferred. 5997status = napi_get_undefined(env, &undefined); 5998if (status != napi_ok) return NULL; 5999 6000// Resolve or reject the promise associated with the deferred depending on 6001// whether the asynchronous action succeeded. 6002if (asynchronous_action_succeeded) { 6003 status = napi_resolve_deferred(env, deferred, undefined); 6004} else { 6005 status = napi_reject_deferred(env, deferred, undefined); 6006} 6007if (status != napi_ok) return NULL; 6008 6009// At this point the deferred has been freed, so we should assign NULL to it. 6010deferred = NULL; 6011``` 6012 6013### `napi_create_promise` 6014 6015<!-- YAML 6016added: v8.5.0 6017napiVersion: 1 6018--> 6019 6020```c 6021napi_status napi_create_promise(napi_env env, 6022 napi_deferred* deferred, 6023 napi_value* promise); 6024``` 6025 6026* `[in] env`: The environment that the API is invoked under. 6027* `[out] deferred`: A newly created deferred object which can later be passed to 6028 `napi_resolve_deferred()` or `napi_reject_deferred()` to resolve resp. reject 6029 the associated promise. 6030* `[out] promise`: The JavaScript promise associated with the deferred object. 6031 6032Returns `napi_ok` if the API succeeded. 6033 6034This API creates a deferred object and a JavaScript promise. 6035 6036### `napi_resolve_deferred` 6037 6038<!-- YAML 6039added: v8.5.0 6040napiVersion: 1 6041--> 6042 6043```c 6044napi_status napi_resolve_deferred(napi_env env, 6045 napi_deferred deferred, 6046 napi_value resolution); 6047``` 6048 6049* `[in] env`: The environment that the API is invoked under. 6050* `[in] deferred`: The deferred object whose associated promise to resolve. 6051* `[in] resolution`: The value with which to resolve the promise. 6052 6053This API resolves a JavaScript promise by way of the deferred object 6054with which it is associated. Thus, it can only be used to resolve JavaScript 6055promises for which the corresponding deferred object is available. This 6056effectively means that the promise must have been created using 6057`napi_create_promise()` and the deferred object returned from that call must 6058have been retained in order to be passed to this API. 6059 6060The deferred object is freed upon successful completion. 6061 6062### `napi_reject_deferred` 6063 6064<!-- YAML 6065added: v8.5.0 6066napiVersion: 1 6067--> 6068 6069```c 6070napi_status napi_reject_deferred(napi_env env, 6071 napi_deferred deferred, 6072 napi_value rejection); 6073``` 6074 6075* `[in] env`: The environment that the API is invoked under. 6076* `[in] deferred`: The deferred object whose associated promise to resolve. 6077* `[in] rejection`: The value with which to reject the promise. 6078 6079This API rejects a JavaScript promise by way of the deferred object 6080with which it is associated. Thus, it can only be used to reject JavaScript 6081promises for which the corresponding deferred object is available. This 6082effectively means that the promise must have been created using 6083`napi_create_promise()` and the deferred object returned from that call must 6084have been retained in order to be passed to this API. 6085 6086The deferred object is freed upon successful completion. 6087 6088### `napi_is_promise` 6089 6090<!-- YAML 6091added: v8.5.0 6092napiVersion: 1 6093--> 6094 6095```c 6096napi_status napi_is_promise(napi_env env, 6097 napi_value value, 6098 bool* is_promise); 6099``` 6100 6101* `[in] env`: The environment that the API is invoked under. 6102* `[in] value`: The value to examine 6103* `[out] is_promise`: Flag indicating whether `promise` is a native promise 6104 object (that is, a promise object created by the underlying engine). 6105 6106## Script execution 6107 6108Node-API provides an API for executing a string containing JavaScript using the 6109underlying JavaScript engine. 6110 6111### `napi_run_script` 6112 6113<!-- YAML 6114added: v8.5.0 6115napiVersion: 1 6116--> 6117 6118```c 6119NAPI_EXTERN napi_status napi_run_script(napi_env env, 6120 napi_value script, 6121 napi_value* result); 6122``` 6123 6124* `[in] env`: The environment that the API is invoked under. 6125* `[in] script`: A JavaScript string containing the script to execute. 6126* `[out] result`: The value resulting from having executed the script. 6127 6128This function executes a string of JavaScript code and returns its result with 6129the following caveats: 6130 6131* Unlike `eval`, this function does not allow the script to access the current 6132 lexical scope, and therefore also does not allow to access the 6133 [module scope][], meaning that pseudo-globals such as `require` will not be 6134 available. 6135* The script can access the [global scope][]. Function and `var` declarations 6136 in the script will be added to the [`global`][] object. Variable declarations 6137 made using `let` and `const` will be visible globally, but will not be added 6138 to the [`global`][] object. 6139* The value of `this` is [`global`][] within the script. 6140 6141## libuv event loop 6142 6143Node-API provides a function for getting the current event loop associated with 6144a specific `napi_env`. 6145 6146### `napi_get_uv_event_loop` 6147 6148<!-- YAML 6149added: 6150 - v9.3.0 6151 - v8.10.0 6152napiVersion: 2 6153--> 6154 6155```c 6156NAPI_EXTERN napi_status napi_get_uv_event_loop(node_api_nogc_env env, 6157 struct uv_loop_s** loop); 6158``` 6159 6160* `[in] env`: The environment that the API is invoked under. 6161* `[out] loop`: The current libuv loop instance. 6162 6163## Asynchronous thread-safe function calls 6164 6165JavaScript functions can normally only be called from a native addon's main 6166thread. If an addon creates additional threads, then Node-API functions that 6167require a `napi_env`, `napi_value`, or `napi_ref` must not be called from those 6168threads. 6169 6170When an addon has additional threads and JavaScript functions need to be invoked 6171based on the processing completed by those threads, those threads must 6172communicate with the addon's main thread so that the main thread can invoke the 6173JavaScript function on their behalf. The thread-safe function APIs provide an 6174easy way to do this. 6175 6176These APIs provide the type `napi_threadsafe_function` as well as APIs to 6177create, destroy, and call objects of this type. 6178`napi_create_threadsafe_function()` creates a persistent reference to a 6179`napi_value` that holds a JavaScript function which can be called from multiple 6180threads. The calls happen asynchronously. This means that values with which the 6181JavaScript callback is to be called will be placed in a queue, and, for each 6182value in the queue, a call will eventually be made to the JavaScript function. 6183 6184Upon creation of a `napi_threadsafe_function` a `napi_finalize` callback can be 6185provided. This callback will be invoked on the main thread when the thread-safe 6186function is about to be destroyed. It receives the context and the finalize data 6187given during construction, and provides an opportunity for cleaning up after the 6188threads e.g. by calling `uv_thread_join()`. **Aside from the main loop thread, 6189no threads should be using the thread-safe function after the finalize callback 6190completes.** 6191 6192The `context` given during the call to `napi_create_threadsafe_function()` can 6193be retrieved from any thread with a call to 6194`napi_get_threadsafe_function_context()`. 6195 6196### Calling a thread-safe function 6197 6198`napi_call_threadsafe_function()` can be used for initiating a call into 6199JavaScript. `napi_call_threadsafe_function()` accepts a parameter which controls 6200whether the API behaves blockingly. If set to `napi_tsfn_nonblocking`, the API 6201behaves non-blockingly, returning `napi_queue_full` if the queue was full, 6202preventing data from being successfully added to the queue. If set to 6203`napi_tsfn_blocking`, the API blocks until space becomes available in the queue. 6204`napi_call_threadsafe_function()` never blocks if the thread-safe function was 6205created with a maximum queue size of 0. 6206 6207`napi_call_threadsafe_function()` should not be called with `napi_tsfn_blocking` 6208from a JavaScript thread, because, if the queue is full, it may cause the 6209JavaScript thread to deadlock. 6210 6211The actual call into JavaScript is controlled by the callback given via the 6212`call_js_cb` parameter. `call_js_cb` is invoked on the main thread once for each 6213value that was placed into the queue by a successful call to 6214`napi_call_threadsafe_function()`. If such a callback is not given, a default 6215callback will be used, and the resulting JavaScript call will have no arguments. 6216The `call_js_cb` callback receives the JavaScript function to call as a 6217`napi_value` in its parameters, as well as the `void*` context pointer used when 6218creating the `napi_threadsafe_function`, and the next data pointer that was 6219created by one of the secondary threads. The callback can then use an API such 6220as `napi_call_function()` to call into JavaScript. 6221 6222The callback may also be invoked with `env` and `call_js_cb` both set to `NULL` 6223to indicate that calls into JavaScript are no longer possible, while items 6224remain in the queue that may need to be freed. This normally occurs when the 6225Node.js process exits while there is a thread-safe function still active. 6226 6227It is not necessary to call into JavaScript via `napi_make_callback()` because 6228Node-API runs `call_js_cb` in a context appropriate for callbacks. 6229 6230Zero or more queued items may be invoked in each tick of the event loop. 6231Applications should not depend on a specific behavior other than progress in 6232invoking callbacks will be made and events will be invoked 6233as time moves forward. 6234 6235### Reference counting of thread-safe functions 6236 6237Threads can be added to and removed from a `napi_threadsafe_function` object 6238during its existence. Thus, in addition to specifying an initial number of 6239threads upon creation, `napi_acquire_threadsafe_function` can be called to 6240indicate that a new thread will start making use of the thread-safe function. 6241Similarly, `napi_release_threadsafe_function` can be called to indicate that an 6242existing thread will stop making use of the thread-safe function. 6243 6244`napi_threadsafe_function` objects are destroyed when every thread which uses 6245the object has called `napi_release_threadsafe_function()` or has received a 6246return status of `napi_closing` in response to a call to 6247`napi_call_threadsafe_function`. The queue is emptied before the 6248`napi_threadsafe_function` is destroyed. `napi_release_threadsafe_function()` 6249should be the last API call made in conjunction with a given 6250`napi_threadsafe_function`, because after the call completes, there is no 6251guarantee that the `napi_threadsafe_function` is still allocated. For the same 6252reason, do not use a thread-safe function 6253after receiving a return value of `napi_closing` in response to a call to 6254`napi_call_threadsafe_function`. Data associated with the 6255`napi_threadsafe_function` can be freed in its `napi_finalize` callback which 6256was passed to `napi_create_threadsafe_function()`. The parameter 6257`initial_thread_count` of `napi_create_threadsafe_function` marks the initial 6258number of acquisitions of the thread-safe functions, instead of calling 6259`napi_acquire_threadsafe_function` multiple times at creation. 6260 6261Once the number of threads making use of a `napi_threadsafe_function` reaches 6262zero, no further threads can start making use of it by calling 6263`napi_acquire_threadsafe_function()`. In fact, all subsequent API calls 6264associated with it, except `napi_release_threadsafe_function()`, will return an 6265error value of `napi_closing`. 6266 6267The thread-safe function can be "aborted" by giving a value of `napi_tsfn_abort` 6268to `napi_release_threadsafe_function()`. This will cause all subsequent APIs 6269associated with the thread-safe function except 6270`napi_release_threadsafe_function()` to return `napi_closing` even before its 6271reference count reaches zero. In particular, `napi_call_threadsafe_function()` 6272will return `napi_closing`, thus informing the threads that it is no longer 6273possible to make asynchronous calls to the thread-safe function. This can be 6274used as a criterion for terminating the thread. **Upon receiving a return value 6275of `napi_closing` from `napi_call_threadsafe_function()` a thread must not use 6276the thread-safe function anymore because it is no longer guaranteed to 6277be allocated.** 6278 6279### Deciding whether to keep the process running 6280 6281Similarly to libuv handles, thread-safe functions can be "referenced" and 6282"unreferenced". A "referenced" thread-safe function will cause the event loop on 6283the thread on which it is created to remain alive until the thread-safe function 6284is destroyed. In contrast, an "unreferenced" thread-safe function will not 6285prevent the event loop from exiting. The APIs `napi_ref_threadsafe_function` and 6286`napi_unref_threadsafe_function` exist for this purpose. 6287 6288Neither does `napi_unref_threadsafe_function` mark the thread-safe functions as 6289able to be destroyed nor does `napi_ref_threadsafe_function` prevent it from 6290being destroyed. 6291 6292### `napi_create_threadsafe_function` 6293 6294<!-- YAML 6295added: v10.6.0 6296napiVersion: 4 6297changes: 6298 - version: 6299 - v12.6.0 6300 - v10.17.0 6301 pr-url: https://github.com/nodejs/node/pull/27791 6302 description: Made `func` parameter optional with custom `call_js_cb`. 6303--> 6304 6305```c 6306NAPI_EXTERN napi_status 6307napi_create_threadsafe_function(napi_env env, 6308 napi_value func, 6309 napi_value async_resource, 6310 napi_value async_resource_name, 6311 size_t max_queue_size, 6312 size_t initial_thread_count, 6313 void* thread_finalize_data, 6314 napi_finalize thread_finalize_cb, 6315 void* context, 6316 napi_threadsafe_function_call_js call_js_cb, 6317 napi_threadsafe_function* result); 6318``` 6319 6320* `[in] env`: The environment that the API is invoked under. 6321* `[in] func`: An optional JavaScript function to call from another thread. It 6322 must be provided if `NULL` is passed to `call_js_cb`. 6323* `[in] async_resource`: An optional object associated with the async work that 6324 will be passed to possible `async_hooks` [`init` hooks][]. 6325* `[in] async_resource_name`: A JavaScript string to provide an identifier for 6326 the kind of resource that is being provided for diagnostic information exposed 6327 by the `async_hooks` API. 6328* `[in] max_queue_size`: Maximum size of the queue. `0` for no limit. 6329* `[in] initial_thread_count`: The initial number of acquisitions, i.e. the 6330 initial number of threads, including the main thread, which will be making use 6331 of this function. 6332* `[in] thread_finalize_data`: Optional data to be passed to `thread_finalize_cb`. 6333* `[in] thread_finalize_cb`: Optional function to call when the 6334 `napi_threadsafe_function` is being destroyed. 6335* `[in] context`: Optional data to attach to the resulting 6336 `napi_threadsafe_function`. 6337* `[in] call_js_cb`: Optional callback which calls the JavaScript function in 6338 response to a call on a different thread. This callback will be called on the 6339 main thread. If not given, the JavaScript function will be called with no 6340 parameters and with `undefined` as its `this` value. 6341 [`napi_threadsafe_function_call_js`][] provides more details. 6342* `[out] result`: The asynchronous thread-safe JavaScript function. 6343 6344**Change History:** 6345 6346* Experimental (`NAPI_EXPERIMENTAL` is defined): 6347 6348 Uncaught exceptions thrown in `call_js_cb` are handled with the 6349 [`'uncaughtException'`][] event, instead of being ignored. 6350 6351### `napi_get_threadsafe_function_context` 6352 6353<!-- YAML 6354added: v10.6.0 6355napiVersion: 4 6356--> 6357 6358```c 6359NAPI_EXTERN napi_status 6360napi_get_threadsafe_function_context(napi_threadsafe_function func, 6361 void** result); 6362``` 6363 6364* `[in] func`: The thread-safe function for which to retrieve the context. 6365* `[out] result`: The location where to store the context. 6366 6367This API may be called from any thread which makes use of `func`. 6368 6369### `napi_call_threadsafe_function` 6370 6371<!-- YAML 6372added: v10.6.0 6373napiVersion: 4 6374changes: 6375 - version: v14.5.0 6376 pr-url: https://github.com/nodejs/node/pull/33453 6377 description: Support for `napi_would_deadlock` has been reverted. 6378 - version: v14.1.0 6379 pr-url: https://github.com/nodejs/node/pull/32689 6380 description: Return `napi_would_deadlock` when called with 6381 `napi_tsfn_blocking` from the main thread or a worker thread 6382 and the queue is full. 6383--> 6384 6385```c 6386NAPI_EXTERN napi_status 6387napi_call_threadsafe_function(napi_threadsafe_function func, 6388 void* data, 6389 napi_threadsafe_function_call_mode is_blocking); 6390``` 6391 6392* `[in] func`: The asynchronous thread-safe JavaScript function to invoke. 6393* `[in] data`: Data to send into JavaScript via the callback `call_js_cb` 6394 provided during the creation of the thread-safe JavaScript function. 6395* `[in] is_blocking`: Flag whose value can be either `napi_tsfn_blocking` to 6396 indicate that the call should block if the queue is full or 6397 `napi_tsfn_nonblocking` to indicate that the call should return immediately 6398 with a status of `napi_queue_full` whenever the queue is full. 6399 6400This API should not be called with `napi_tsfn_blocking` from a JavaScript 6401thread, because, if the queue is full, it may cause the JavaScript thread to 6402deadlock. 6403 6404This API will return `napi_closing` if `napi_release_threadsafe_function()` was 6405called with `abort` set to `napi_tsfn_abort` from any thread. The value is only 6406added to the queue if the API returns `napi_ok`. 6407 6408This API may be called from any thread which makes use of `func`. 6409 6410### `napi_acquire_threadsafe_function` 6411 6412<!-- YAML 6413added: v10.6.0 6414napiVersion: 4 6415--> 6416 6417```c 6418NAPI_EXTERN napi_status 6419napi_acquire_threadsafe_function(napi_threadsafe_function func); 6420``` 6421 6422* `[in] func`: The asynchronous thread-safe JavaScript function to start making 6423 use of. 6424 6425A thread should call this API before passing `func` to any other thread-safe 6426function APIs to indicate that it will be making use of `func`. This prevents 6427`func` from being destroyed when all other threads have stopped making use of 6428it. 6429 6430This API may be called from any thread which will start making use of `func`. 6431 6432### `napi_release_threadsafe_function` 6433 6434<!-- YAML 6435added: v10.6.0 6436napiVersion: 4 6437--> 6438 6439```c 6440NAPI_EXTERN napi_status 6441napi_release_threadsafe_function(napi_threadsafe_function func, 6442 napi_threadsafe_function_release_mode mode); 6443``` 6444 6445* `[in] func`: The asynchronous thread-safe JavaScript function whose reference 6446 count to decrement. 6447* `[in] mode`: Flag whose value can be either `napi_tsfn_release` to indicate 6448 that the current thread will make no further calls to the thread-safe 6449 function, or `napi_tsfn_abort` to indicate that in addition to the current 6450 thread, no other thread should make any further calls to the thread-safe 6451 function. If set to `napi_tsfn_abort`, further calls to 6452 `napi_call_threadsafe_function()` will return `napi_closing`, and no further 6453 values will be placed in the queue. 6454 6455A thread should call this API when it stops making use of `func`. Passing `func` 6456to any thread-safe APIs after having called this API has undefined results, as 6457`func` may have been destroyed. 6458 6459This API may be called from any thread which will stop making use of `func`. 6460 6461### `napi_ref_threadsafe_function` 6462 6463<!-- YAML 6464added: v10.6.0 6465napiVersion: 4 6466--> 6467 6468```c 6469NAPI_EXTERN napi_status 6470napi_ref_threadsafe_function(node_api_nogc_env env, napi_threadsafe_function func); 6471``` 6472 6473* `[in] env`: The environment that the API is invoked under. 6474* `[in] func`: The thread-safe function to reference. 6475 6476This API is used to indicate that the event loop running on the main thread 6477should not exit until `func` has been destroyed. Similar to [`uv_ref`][] it is 6478also idempotent. 6479 6480Neither does `napi_unref_threadsafe_function` mark the thread-safe functions as 6481able to be destroyed nor does `napi_ref_threadsafe_function` prevent it from 6482being destroyed. `napi_acquire_threadsafe_function` and 6483`napi_release_threadsafe_function` are available for that purpose. 6484 6485This API may only be called from the main thread. 6486 6487### `napi_unref_threadsafe_function` 6488 6489<!-- YAML 6490added: v10.6.0 6491napiVersion: 4 6492--> 6493 6494```c 6495NAPI_EXTERN napi_status 6496napi_unref_threadsafe_function(node_api_nogc_env env, napi_threadsafe_function func); 6497``` 6498 6499* `[in] env`: The environment that the API is invoked under. 6500* `[in] func`: The thread-safe function to unreference. 6501 6502This API is used to indicate that the event loop running on the main thread 6503may exit before `func` is destroyed. Similar to [`uv_unref`][] it is also 6504idempotent. 6505 6506This API may only be called from the main thread. 6507 6508## Miscellaneous utilities 6509 6510### `node_api_get_module_file_name` 6511 6512<!-- YAML 6513added: 6514 - v15.9.0 6515 - v14.18.0 6516 - v12.22.0 6517napiVersion: 9 6518--> 6519 6520```c 6521NAPI_EXTERN napi_status 6522node_api_get_module_file_name(node_api_nogc_env env, const char** result); 6523 6524``` 6525 6526* `[in] env`: The environment that the API is invoked under. 6527* `[out] result`: A URL containing the absolute path of the 6528 location from which the add-on was loaded. For a file on the local 6529 file system it will start with `file://`. The string is null-terminated and 6530 owned by `env` and must thus not be modified or freed. 6531 6532`result` may be an empty string if the add-on loading process fails to establish 6533the add-on's file name during loading. 6534 6535[ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/ 6536[AppVeyor]: https://www.appveyor.com 6537[C++ Addons]: addons.md 6538[CMake]: https://cmake.org 6539[CMake.js]: https://github.com/cmake-js/cmake-js 6540[ECMAScript Language Specification]: https://tc39.github.io/ecma262/ 6541[Error handling]: #error-handling 6542[GCC]: https://gcc.gnu.org 6543[GYP]: https://gyp.gsrc.io 6544[GitHub releases]: https://help.github.com/en/github/administering-a-repository/about-releases 6545[LLVM]: https://llvm.org 6546[Native Abstractions for Node.js]: https://github.com/nodejs/nan 6547[Node-API Media]: https://github.com/nodejs/abi-stable-node/blob/HEAD/node-api-media.md 6548[Object lifetime management]: #object-lifetime-management 6549[Object wrap]: #object-wrap 6550[Section 12.10.4]: https://tc39.github.io/ecma262/#sec-instanceofoperator 6551[Section 12.5.5]: https://tc39.github.io/ecma262/#sec-typeof-operator 6552[Section 19.2]: https://tc39.github.io/ecma262/#sec-function-objects 6553[Section 19.4]: https://tc39.github.io/ecma262/#sec-symbol-objects 6554[Section 20.3]: https://tc39.github.io/ecma262/#sec-date-objects 6555[Section 22.1]: https://tc39.github.io/ecma262/#sec-array-objects 6556[Section 22.1.4.1]: https://tc39.github.io/ecma262/#sec-properties-of-array-instances-length 6557[Section 22.2]: https://tc39.github.io/ecma262/#sec-typedarray-objects 6558[Section 24.1]: https://tc39.github.io/ecma262/#sec-arraybuffer-objects 6559[Section 24.1.1.2]: https://tc39.es/ecma262/#sec-isdetachedbuffer 6560[Section 24.1.1.3]: https://tc39.es/ecma262/#sec-detacharraybuffer 6561[Section 24.3]: https://tc39.github.io/ecma262/#sec-dataview-objects 6562[Section 25.4]: https://tc39.github.io/ecma262/#sec-promise-objects 6563[Section 6]: https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values 6564[Section 6.1]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types 6565[Section 6.1.4]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type 6566[Section 6.1.6]: https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type 6567[Section 6.1.7]: https://tc39.github.io/ecma262/#sec-object-type 6568[Section 6.1.7.1]: https://tc39.github.io/ecma262/#table-2 6569[Section 7]: https://tc39.github.io/ecma262/#sec-abstract-operations 6570[Section 7.1.13]: https://tc39.github.io/ecma262/#sec-toobject 6571[Section 7.1.2]: https://tc39.github.io/ecma262/#sec-toboolean 6572[Section 7.1.3]: https://tc39.github.io/ecma262/#sec-tonumber 6573[Section 7.2.14]: https://tc39.github.io/ecma262/#sec-strict-equality-comparison 6574[Section 7.2.2]: https://tc39.github.io/ecma262/#sec-isarray 6575[Section 8.7]: https://tc39.es/ecma262/#sec-agents 6576[Section 9.1.6]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc 6577[Travis CI]: https://travis-ci.org 6578[Visual Studio]: https://visualstudio.microsoft.com 6579[Working with JavaScript properties]: #working-with-javascript-properties 6580[Xcode]: https://developer.apple.com/xcode/ 6581[`'uncaughtException'`]: process.md#event-uncaughtexception 6582[`Number.MAX_SAFE_INTEGER`]: https://tc39.github.io/ecma262/#sec-number.max_safe_integer 6583[`Number.MIN_SAFE_INTEGER`]: https://tc39.github.io/ecma262/#sec-number.min_safe_integer 6584[`Worker`]: worker_threads.md#class-worker 6585[`async_hooks.executionAsyncResource()`]: async_hooks.md#async_hooksexecutionasyncresource 6586[`build_with_cmake`]: https://github.com/nodejs/node-addon-examples/tree/main/build_with_cmake 6587[`global`]: globals.md#global 6588[`init` hooks]: async_hooks.md#initasyncid-type-triggerasyncid-resource 6589[`napi_add_async_cleanup_hook`]: #napi_add_async_cleanup_hook 6590[`napi_add_env_cleanup_hook`]: #napi_add_env_cleanup_hook 6591[`napi_add_finalizer`]: #napi_add_finalizer 6592[`napi_async_cleanup_hook`]: #napi_async_cleanup_hook 6593[`napi_async_complete_callback`]: #napi_async_complete_callback 6594[`napi_async_destroy`]: #napi_async_destroy 6595[`napi_async_init`]: #napi_async_init 6596[`napi_callback`]: #napi_callback 6597[`napi_cancel_async_work`]: #napi_cancel_async_work 6598[`napi_close_callback_scope`]: #napi_close_callback_scope 6599[`napi_close_escapable_handle_scope`]: #napi_close_escapable_handle_scope 6600[`napi_close_handle_scope`]: #napi_close_handle_scope 6601[`napi_create_async_work`]: #napi_create_async_work 6602[`napi_create_error`]: #napi_create_error 6603[`napi_create_external_arraybuffer`]: #napi_create_external_arraybuffer 6604[`napi_create_range_error`]: #napi_create_range_error 6605[`napi_create_reference`]: #napi_create_reference 6606[`napi_create_type_error`]: #napi_create_type_error 6607[`napi_define_class`]: #napi_define_class 6608[`napi_delete_async_work`]: #napi_delete_async_work 6609[`napi_delete_reference`]: #napi_delete_reference 6610[`napi_escape_handle`]: #napi_escape_handle 6611[`napi_finalize`]: #napi_finalize 6612[`napi_get_and_clear_last_exception`]: #napi_get_and_clear_last_exception 6613[`napi_get_array_length`]: #napi_get_array_length 6614[`napi_get_element`]: #napi_get_element 6615[`napi_get_last_error_info`]: #napi_get_last_error_info 6616[`napi_get_property`]: #napi_get_property 6617[`napi_get_reference_value`]: #napi_get_reference_value 6618[`napi_get_typedarray_info`]: #napi_get_typedarray_info 6619[`napi_get_value_external`]: #napi_get_value_external 6620[`napi_has_property`]: #napi_has_property 6621[`napi_instanceof`]: #napi_instanceof 6622[`napi_is_error`]: #napi_is_error 6623[`napi_is_exception_pending`]: #napi_is_exception_pending 6624[`napi_is_typedarray`]: #napi_is_typedarray 6625[`napi_make_callback`]: #napi_make_callback 6626[`napi_open_callback_scope`]: #napi_open_callback_scope 6627[`napi_open_escapable_handle_scope`]: #napi_open_escapable_handle_scope 6628[`napi_open_handle_scope`]: #napi_open_handle_scope 6629[`napi_property_attributes`]: #napi_property_attributes 6630[`napi_property_descriptor`]: #napi_property_descriptor 6631[`napi_queue_async_work`]: #napi_queue_async_work 6632[`napi_reference_ref`]: #napi_reference_ref 6633[`napi_reference_unref`]: #napi_reference_unref 6634[`napi_remove_async_cleanup_hook`]: #napi_remove_async_cleanup_hook 6635[`napi_remove_env_cleanup_hook`]: #napi_remove_env_cleanup_hook 6636[`napi_set_instance_data`]: #napi_set_instance_data 6637[`napi_set_property`]: #napi_set_property 6638[`napi_threadsafe_function_call_js`]: #napi_threadsafe_function_call_js 6639[`napi_throw_error`]: #napi_throw_error 6640[`napi_throw_range_error`]: #napi_throw_range_error 6641[`napi_throw_type_error`]: #napi_throw_type_error 6642[`napi_throw`]: #napi_throw 6643[`napi_unwrap`]: #napi_unwrap 6644[`napi_wrap`]: #napi_wrap 6645[`node-addon-api`]: https://github.com/nodejs/node-addon-api 6646[`node_api.h`]: https://github.com/nodejs/node/blob/HEAD/src/node_api.h 6647[`node_api_create_external_string_latin1`]: #node_api_create_external_string_latin1 6648[`node_api_create_external_string_utf16`]: #node_api_create_external_string_utf16 6649[`node_api_create_syntax_error`]: #node_api_create_syntax_error 6650[`node_api_nogc_finalize`]: #node_api_nogc_finalize 6651[`node_api_post_finalizer`]: #node_api_post_finalizer 6652[`node_api_throw_syntax_error`]: #node_api_throw_syntax_error 6653[`process.release`]: process.md#processrelease 6654[`uv_ref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_ref 6655[`uv_unref`]: https://docs.libuv.org/en/v1.x/handle.html#c.uv_unref 6656[`worker.terminate()`]: worker_threads.md#workerterminate 6657[async_hooks `type`]: async_hooks.md#type 6658[context-aware addons]: addons.md#context-aware-addons 6659[docs]: https://github.com/nodejs/node-addon-api#api-documentation 6660[external]: #napi_create_external 6661[externals]: #napi_create_external 6662[global scope]: globals.md 6663[gyp-next]: https://github.com/nodejs/gyp-next 6664[module scope]: modules.md#the-module-scope 6665[node-gyp]: https://github.com/nodejs/node-gyp 6666[node-pre-gyp]: https://github.com/mapbox/node-pre-gyp 6667[prebuild]: https://github.com/prebuild/prebuild 6668[prebuildify]: https://github.com/prebuild/prebuildify 6669[worker threads]: https://nodejs.org/api/worker_threads.html 6670