1# Node-API Data Types and APIs 2 3## Data Types 4 5### napi_status 6 7Enum indicating the success or failure of a Node-API call. 8 9```c 10typedef enum { 11 napi_ok, 12 napi_invalid_arg, 13 napi_object_expected, 14 napi_string_expected, 15 napi_name_expected, 16 napi_function_expected, 17 napi_number_expected, 18 napi_boolean_expected, 19 napi_array_expected, 20 napi_generic_failure, 21 napi_pending_exception, 22 napi_cancelled, 23 napi_escape_called_twice, 24 napi_handle_scope_mismatch, 25 napi_callback_scope_mismatch, 26 napi_queue_full, 27 napi_closing, 28 napi_bigint_expected, 29 napi_date_expected, 30 napi_arraybuffer_expected, 31 napi_detachable_arraybuffer_expected, 32 napi_would_deadlock, /* unused */ 33 napi_no_external_buffers_allowed, 34 napi_cannot_run_js 35} napi_status; 36``` 37 38### napi_extended_error_info 39 40Struct that holds detailed error information when a Node-API call fails. 41 42```c 43typedef struct { 44 const char *error_message; 45 void *engine_reserved; 46 uint32_t engine_error_code; 47 napi_status error_code; 48} napi_extended_error_info; 49``` 50 51### napi_value 52 53Pointer used to represent a JavaScript (JS) value. 54 55### napi_env 56 57- Context used by the underlying Node-API implementation. It is passed to the native functions when they are invoked, and must be passed back when Node-API calls are made. 58 59- The **napi_env** becomes invalid when an instance of the native addon is unloaded. A notification of this event is sent through the callbacks given to **napi_add_env_cleanup_hook** and **napi_set_instance_data**. 60 61- Avoid caching **napi_env** or passing **napi_env** between instances of the same addon running on different worker threads. 62 63### napi_threadsafe_function 64 65Pointer that represents a JS function that can be called asynchronously from multiple threads. It can be used to pass the asynchronous operation result to the JS environment, such as reading data from another thread or performing compute-intensive operations. In addition, it can be used to call functions in C++ code from a JS environment for execution in another thread. By using **napi_threadsafe_function**, you can implement efficient interaction between JS and C++ code while maintaining thread safety. 66 67### napi_threadsafe_function_release_mode 68 69Enum that indicates when to release the thread-safe function. 70 71```c 72typedef enum { 73 napi_tsfn_release, 74 napi_tsfn_abort 75} napi_threadsafe_function_release_mode; 76``` 77 78Its value is passed to **napi_release_threadsafe_function**. 79 80```cpp 81napi_release_threadsafe_function(napi_threadsafe_function func, 82 napi_threadsafe_function_release_mode mode); 83``` 84 85- If the value is **napi_tsfn_release**, the current thread will not call this thread-safe function. 86 87- If the value is **napi_tsfn_abort**, only the current thread can call this thread-safe function. 88 In this case, using **napi_call_threadsafe_function** to call this function will return **napi_closing**, and this function will not be placed in the queue. 89 90### napi_threadsafe_function_call_mode 91 92Enum that indicates whether the call should be blocked when the queue associated with the thread-safe function is full. 93 94The data struct is as follows: 95 96```c 97typedef enum { 98 napi_tsfn_nonblocking, 99 napi_tsfn_blocking 100} napi_threadsafe_function_call_mode; 101``` 102 103- **napi_tsfn_nonblocking**: Leave **napi_call_threadsafe_function** unblocked. If the queue is full, **napi_queue_full** is returned to prevent data from being added to the queue. 104 105- **napi_tsfn_blocking**: Block **napi_call_threadsafe_function** until there is available space in the queue. 106 107### Memory Management Types 108 109Node-API provides the following memory management types: 110 111**napi_handle_scope** 112 113Data used to manage the lifecycle of JS objects. It allows JS objects to remain active within a certain range for use in JS code. When **napi_handle_scope** is created, all JS objects created in this range remain active until the end. This can prevent released objects from being used in JS code, which improves code reliability and performance. 114 115**napi_escapable_handle_scope** 116 117- It is created by **napi_open_escapable_handle_scope** and closed by **napi_close_escapable_handle_scope**. 118 119- It is a special type of handle range used to return values created within the scope of **escapable_handle_scope** to a parent scope. 120 121- You can use **napi_escape_handle** to promote **escape_handle_scope** to a JS object so that it is valid for the lifetime of the outer scope. 122 123**napi_ref** 124 125Reference to **napi_value**, which allows you to manage the lifecycle of JS values. 126 127**napi_type_tag** 128 129Struct containing two unsigned 64-bit integers to identify the type of a Node-API value. 130 131```c 132typedef struct { 133 uint64_t lower; 134 uint64_t upper; 135} napi_type_tag; 136``` 137 138- It is a 128-bit value stored as two unsigned 64-bit integers. It is used to tag JS objects to ensure that they are of a certain type. 139 140- This is a stronger check than **napi_instanceof** because **napi_instanceof** may report a false positive if the object's prototype is manipulated. 141 142- The combination of **type_tag** and **napi_wrap** is useful because it ensures that the pointer retrieved from a wrapped object can be safely converted to the native type corresponding to the type tag that had been previously applied to the JS object. 143 144**napi_async_cleanup_hook_handle** 145 146Value used to register a callback for an asynchronous operation. It is mainly used to perform a cleanup operation when an asynchronous operation is complete or canceled, for example, releasing a resource or canceling an operation. Using **napi_async_cleanup_hook_handle** ensures that related resources are correctly released and cleaned up when an asynchronous operation is complete or canceled, thereby avoiding problems such as memory leakage. 147 148### Callback Types 149 150Node-API provides the following callback types: 151 152**napi_callback_info** 153 154Data type passed to **napi_get_cb_info** to obtain JS input parameters. 155 156**napi_callback** 157 158User-defined native function, which is exposed to JS via Node-API. Generally, no handle or callback scope is created inside this callback. 159 160The basic usage is as follows: 161 162```c 163typedef napi_value (*napi_callback)(napi_env, napi_callback_info); 164``` 165 166**napi_finalize** 167 168Function pointer passed to **napi_create_threadsafe_function** and **napi_set_instance_data**. **napi_finalize** is called when an object is reclaimed. 169 170**napi_async_execute_callback** 171 172Function pointer used in **napi_create_async_work**. 173 174- An asynchronous native function is called from a worker pool thread and can be executed in parallel with the main event loop thread. 175 176- Avoid making Node-API calls that execute JS code or interact with JS objects when implementing this callback. 177 178- Node-API calls should be executed in **napi_async_complete_callback**. 179 180**napi_async_complete_callback** 181 182Function pointer used when an asynchronous operation is complete. It is usually used in C++ addon development of Node.js. When an asynchronous operation is required, you can use **napi_create_async_work** to create an asynchronous operation work object and specify a **napi_async_complete_callback** callback. When the asynchronous operation is complete, the callback is automatically called for subsequent processing. Parameters of the callback include the status of the asynchronous operation and a return value, based on which corresponding processing can be performed. 183 184**napi_threadsafe_function_call_js** 185 186Function pointer used in the main thread to interact with the JS code in an independent thread to implement more complex scenarios. It is used in **napi_create_threadsafe_function(napi_env env, ..., napi_threadsafe_function_call_js call_js_cb, ...)**. 187 188**napi_cleanup_hook** 189 190Function pointer used with **napi_add_env_cleanup_hook**. It will be called when the environment is destroyed. 191 192**napi_async_cleanup_hook** 193 194Function pointer used with **napi_add_async_cleanup_hook**. It will be called when the environment is destroyed. 195 196### QoS 197 198Enum indicating the thread scheduling priority. 199 200```c 201typedef enum { 202 napi_qos_background = 0, 203 napi_qos_utility = 1, 204 napi_qos_default = 2, 205 napi_qos_user_initiated = 3, 206} napi_qos_t; 207``` 208 209| QoS| Use Scenario| 210| -------- | -------- | 211| napi_qos_background | Low priority for works invisible to users, such as data synchronization and backup.| 212| napi_qos_utility | Medium priority for works that do not require immediate response, such as downloading or importing data. | 213| napi_qos_default | Default priority.| 214| napi_qos_user_initiated | High priority for user-triggered works with visible progress, for example, opening a file.| 215 216 217## APIs 218 219Node-API is extended based on the native modules provided by Node.js. The following lists the APIs supported currently. 220 221### Asynchronous Thread-Safe APIs 222 223| API| Description| 224| -------- | -------- | 225| napi_create_threadsafe_function | Creates a thread-safe function.| 226| napi_get_threadsafe_function_context | Obtains the context of a thread-safe function.| 227| napi_call_threadsafe_function | Calls a thread-safe function.| 228| napi_acquire_threadsafe_function | Acquires a thread-safe function.| 229| napi_release_threadsafe_function | Releases a thread-safe function.| 230| napi_ref_threadsafe_function | Indicates that the event loop running on the main thread should not exit until the thread-safe function is destroyed.| 231| napi_unref_threadsafe_function | Indicates that the event loop running on the main thread may exit before the thread-safe function is destroyed.| 232 233### Buffer 234 235| API| Description| 236| -------- | -------- | 237| napi_create_buffer | Creates a JS buffer of the specified size.| 238| napi_create_buffer_copy | Creates a JS buffer of the specified size, and initializes it with data copied from the passed-in buffer.| 239| napi_create_external_buffer | Creates a JS buffer of the specified size, and initializes it with the given data.| 240| napi_get_buffer_info | Obtains the underlying data of a JS buffer and its length.| 241| napi_is_buffer | Checks whether the given JS value is a **Buffer** object.| 242| napi_create_external_arraybuffer | Allocates a JS ArrayBuffer with external data.| 243 244### String 245 246| API| Description| 247| -------- | -------- | 248| napi_create_string_utf16 | Creates a JS string from a UTF16-encoded C string.| 249| napi_get_value_string_utf16 | Obtains the UTF16-encoded string corresponding to the given JS value.| 250| napi_create_string_latin1 | Creates a JS string from an ISO-8859-1-encoded C string.| 251| napi_create_string_utf8 | Creates a JS string from a UTF8-encoded C string.| 252| napi_get_value_string_latin1 | Obtains the ISO-8859-1-encoded string corresponding to the given JS value.| 253| napi_get_value_string_utf8 | Obtains the UTF8-encoded string corresponding to the given JS value.| 254 255### Date 256 257| API| Description| 258| -------- | -------- | 259| napi_create_date | Creates a JS **Date** object from C double data.| 260| napi_get_date_value | Obtains the C double equivalent of the given JS **Date** object.| 261| napi_is_date | Checks whether the given JS value is a JS **Date** object.| 262 263### ArrayBuffer 264 265| API| Description| 266| -------- | -------- | 267| napi_get_arraybuffer_info | Obtains the underlying data buffer of an **ArrayBuffer** and its length.| 268| napi_is_arraybuffer | Checks whether the given JS value is an **ArrayBuffer** object.| 269| napi_detach_arraybuffer | Detaches the underlying data of the given **ArrayBuffer**.| 270| napi_is_detached_arraybuffer | Checks whether the given **ArrayBuffer** has been detached.| 271| napi_create_arraybuffer | Creates a JS **ArrayBuffer** object of the specified size.| 272 273### Module 274 275| API| Description| 276| -------- | -------- | 277| napi_module_register | Registers a native module.| 278 279### Lifecycle Management 280 281| API| Description| 282| -------- | -------- | 283| napi_open_handle_scope | Opens a scope. You can use **napi_close_handle_scope** to close it.| 284| napi_close_handle_scope | Closes the scope passed in. After a scope is closed, all references declared in it are closed.| 285| napi_open_escapable_handle_scope | Opens a scope from which one object can be prompted to the outer scope. You can use **napi_close_escapable_handle_scope** to close it.| 286| napi_close_escapable_handle_scope | Closes the escapable handle scope passed in.| 287| napi_escape_handle | Promotes the handle to the JS object so that it is valid for the lifetime of the outer scope.| 288| napi_create_reference | Creates a reference for an object to extend its lifespan. The caller needs to manage the reference lifespan.| 289| napi_delete_reference | Deletes the reference passed in.| 290| napi_reference_ref | Increments the reference count passed in and returns the count.| 291| napi_reference_unref | Decrements the reference count passed in and returns the count.| 292| napi_get_reference_value | Obtains the JS object associated with the reference.| 293| napi_add_finalizer | Adds a **napi_finalize** callback, which will be called when the JS object in **js_Object** is garbage-collected.| 294 295### Promise 296 297| API| Description| 298| -------- | -------- | 299| napi_create_promise | Creates a deferred object and a JS promise.| 300| napi_resolve_deferred | Resolves a promise by way of the deferred object associated.| 301| napi_reject_deferred | Rejects a promise by way of the deferred object associated.| 302| napi_is_promise | Checks whether the given **napi_value** is a promise object.| 303 304### Array 305 306| API| Description| 307| -------- | -------- | 308| napi_create_array | Creates a JS **Array**.| 309| napi_create_array_with_length | Creates a JS **Array** of the specified length.| 310| napi_create_typedarray | Creates a JS **TypedArray** from an existing **ArrayBuffer**.| 311| napi_create_dataview | Creates a JS **DataView** from an existing **ArrayBuffer**.| 312| napi_get_array_length | Obtains the length of an array.| 313| napi_get_typedarray_info | Obtains the properties of a **TypedArray**.| 314| napi_get_dataview_info | Obtains the properties of a **DataView**.| 315| napi_is_array | Checks whether the given JS value is an **Array** object.| 316| napi_set_element | Sets an element at the specified index of the given **Object**.| 317| napi_get_element | Obtains the element at the specified index of the given **Object**.| 318| napi_has_element | Checks whether the given **Object** has an element at the specified index.| 319| napi_delete_element | Deletes the element at the specified index of the given **Object**.| 320 321### Primitives 322 323| API| Description| 324| -------- | -------- | 325| napi_get_boolean | Obtains a JS Boolean object based on the given C Boolean value.| 326| napi_get_global | Obtains the **global** object.| 327| napi_get_null | Obtains the **null** object.| 328| napi_get_undefined | Obtains the **undefined** object.| 329| napi_coerce_to_bool | Forcibly converts a JS value into a JS Boolean value.| 330| napi_coerce_to_number | Forcibly converts a JS value into a JS number.| 331| napi_coerce_to_object | Forcibly converts a JS value into a JS object.| 332| napi_coerce_to_string | Forcibly converts a JS value into a JS string.| 333 334### Class 335 336| API| Description| 337| -------- | -------- | 338| napi_get_new_target | Obtains the **new.target** of the constructor call.| 339| napi_define_class | Defines a JS class corresponding to the C++ class.| 340| napi_new_instance | Creates an instance based on the given constructor.| 341 342### Object 343 344| API| Description| 345| -------- | -------- | 346| napi_get_prototype | Obtains the prototype of a JS object.| 347| napi_create_object | Creates a default JS object.| 348| napi_object_freeze | Freezes an object.| 349| napi_object_seal | Seals an object.| 350| napi_typeof | Obtains the JS type of a JS value.| 351| napi_instanceof | Checks whether the given object is an instance of the specified constructor.| 352| napi_type_tag_object | Associates the value of the tag pointer with a JS object.| 353| napi_check_object_type_tag | Checks whether a tag pointer is associated with a JS object.| 354 355### BigInt 356 357| API| Description| 358| -------- | -------- | 359| napi_create_bigint_int64 | Creates a JS BigInt from C int64 data.| 360| napi_create_bigint_uint64 | Creates a JS BigInt from C uint64 data.| 361| napi_create_bigint_words | Creates a single JS BigInt from a C uint64 array.| 362| napi_get_value_bigint_int64 | Obtains the C int64 equivalent of a JS BigInt.| 363| napi_get_value_bigint_uint64 | Obtains the C uint64 equivalent of a JS BigInt.| 364| napi_get_value_bigint_words | Obtains information from a JS BigInt, including the sign bit, 64-bit little-endian array, and number of elements in the array.| 365 366### Exceptions and Errors 367 368| API| Description| 369| -------- | -------- | 370| napi_throw | Throws a JS value.| 371| napi_throw_type_error | Throws a JS type error with text information.| 372| napi_throw_range_error | Throws a JS range error with text information.| 373| napi_is_error | Checks whether **napi_value** indicates an error object.| 374| napi_create_error | Creates a JS **Error** with text information.| 375| napi_create_type_error | Creates a JS **TypeError** with text information.| 376| napi_create_range_error | Creates a JS **RangeError** with text information.| 377| napi_get_and_clear_last_exception | Obtains and clears the latest exception.| 378| napi_is_exception_pending | Checks whether an exception occurs.| 379| napi_fatal_error | Raises a fatal error to terminate the process immediately.| 380| napi_get_last_error_info | Obtains the **napi_extended_error_info** struct, which contains the latest error information.| 381 382### Property 383 384| API| Description| 385| -------- | -------- | 386| napi_get_property_names | Obtains the names of the enumerable properties of an object in an array of strings.| 387| napi_set_property | Sets a property for an object.| 388| napi_get_property | Obtains the requested property of an object.| 389| napi_has_property | Checks whether an object has the specified property.| 390| napi_delete_property | Deletes the **key** property from an object.| 391| napi_has_own_property | Checks whether an object has the own property named **key**.| 392| napi_set_named_property | Sets a property with the specified name for an object.| 393| napi_get_named_property | Obtains the property with the specified name in an object.| 394| napi_has_named_property | Checks whether an object has the property with the specified name.| 395| napi_define_properties | Defines multiple properties for an object.| 396| napi_get_all_property_names | Obtains an array containing the names of all the available properties of this object.| 397 398### Asynchronous Works 399 400| API| Description| 401| -------- | -------- | 402| napi_create_async_work | Creates a work object that executes logic asynchronously.| 403| napi_delete_async_work | Releases an asynchronous work object.| 404| napi_queue_async_work | Adds an asynchronous work object to the queue so that it can be scheduled for execution.| 405| napi_cancel_async_work | Cancels a queued asynchronous work if it has not been started.| 406 407### Custom Asynchronous Operations 408 409| API| Description| 410| -------- | -------- | 411| napi_async_init | Creates an asynchronous context. The capabilities related to **async_hook** are not supported currently.| 412| napi_make_callback | Allows a JS function to be called in the asynchronous context. The capabilities related to **async_hook** are not supported currently.| 413| napi_async_destroy | Destroys the previously created asynchronous context. The capabilities related to **async_hook** are not supported currently.| 414| napi_open_callback_scope | Opens a callback scope. The capabilities related to **async_hook** are not supported currently.| 415| napi_close_callback_scope | Closes the callback scope. The capabilities related to **async_hook** are not supported currently.| 416 417### Comparing JS Values 418 419| API| Description| 420| -------- | -------- | 421| napi_strict_equals | Checks whether two JS values are strictly equal.| 422 423### UV 424 425| API| Description| 426| -------- | -------- | 427| napi_get_uv_event_loop | Obtains the current libuv loop instance.| 428 429### Function Invocation 430 431| API| Description| 432| -------- | -------- | 433| napi_call_function | Calls a JS function from a C/C++ addon.| 434| napi_get_cb_info | Obtains detailed information about the call, such as the parameters and **this** pointer, from the given callback info.| 435 436### Extension 437 438| API| Description| 439| -------- | -------- | 440| napi_queue_async_work_with_qos | Adds an asynchronous work object to the queue and schedules it based on the QoS passed in.| 441| napi_run_script_path | Runs an .abc file.| 442| napi_load_module | Loads an .abc file as a module. This API returns the namespace of the module.| 443| napi_create_object_with_properties | Creates a JS object using the given **napi_property_descriptor**. The key of the descriptor must be a string and cannot be converted into a number.| 444| napi_create_object_with_named_properties | Creates a JS object using the given **napi_value** and key. The key must be a string and cannot be converted into a number.| 445| napi_coerce_to_native_binding_object | Forcibly binds a JS object and a native object.| 446 447#### napi_queue_async_work_with_qos 448 449```c 450napi_status napi_queue_async_work_with_qos(napi_env env, 451 napi_async_work work, 452 napi_qos_t qos); 453``` 454 455This API has the same usage as **napi_queue_async_work**. The difference is you can specify the QoS for the work to run. 456 457#### napi_run_script_path 458 459```c 460napi_status napi_run_script_path(napi_env env, 461 const char* abcPath, 462 napi_value* result); 463``` 464 465#### napi_load_module 466 467```c 468napi_status napi_load_module(napi_env env, 469 const char* path, 470 napi_value* result); 471``` 472 473#### napi_create_object_with_properties 474 475```c 476napi_status napi_create_object_with_properties(napi_env env, 477 napi_value* result, 478 size_t property_count, 479 const napi_property_descriptor* properties); 480``` 481 482#### napi_create_object_with_named_properties 483 484```c 485napi_status napi_create_object_with_named_properties(napi_env env, 486 napi_value* result, 487 size_t property_count, 488 const char** keys, 489 const napi_value* values); 490``` 491 492#### napi_coerce_to_native_binding_object 493 494```c 495napi_status napi_coerce_to_native_binding_object(napi_env env, 496 napi_value js_object, 497 napi_native_binding_detach_callback detach_cb, 498 napi_native_binding_attach_callback attach_cb, 499 void* native_object, 500 void* hint); 501``` 502 503### Environment Lifecycle 504 505| API| Description| 506| -------- | -------- | 507| napi_set_instance_data | Associates data with the currently running environment.| 508| napi_get_instance_data | Retrieves the data that was previously associated with the currently running environment.| 509 510### Object Lifetime Management 511 512| API| Description| 513| -------- | -------- | 514| napi_add_env_cleanup_hook | Registers a clean-up hook for releasing resources when the environment exits.| 515| napi_remove_env_cleanup_hook | Unregisters the clean-up hook.| 516| napi_add_async_cleanup_hook | Registers an asynchronous clean-up hook for releasing resources when the environment exits.| 517| napi_remove_async_cleanup_hook | Unregisters the asynchronous clean-up hook.| 518 519 520### Other Utilities 521 522| API| Description| 523| -------- | -------- | 524| node_api_get_module_file_name | Obtains the absolute path of the location, from which the addon is loaded.| 525