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