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