1# Performing Lifecycle Management Using Node-API
2
3## Introduction
4
5In Node-API, **napi_value** is an abstract data type that represents an ArkTS value of any type, which includes the basic type (such as number, string, or Boolean) and the composite type (such as array, function, or object).
6
7The **napi_value** lifecycle is closely related to the lifecycle of the ArkTS value. When an ArkTS value is garbage-collected, the **napi_value** associated with it is no longer valid. Avoid using the **napi_value** when the ArkTS value no longer exists.
8
9Scope is used to manage the **napi_value** lifecycle in the framework layer. You can use **napi_open_handle_scope** to open a scope and use **napi_close_handle_scope** to close it. By creating a **napi_value** in a scope, you can ensure that the **napi_value** is automatically released when the scope ends. This helps prevent memory leaks.
10
11**napi_ref** is a Node-API type used to manage the **napi_value** lifecycle. It allows reference to a **napi_value** during its lifecycle, even if the value is beyond its original context. The reference allows a **napi_value** to be shared in different contexts and released in a timely manner.
12
13## Basic Concepts
14
15Node-API provides APIs for creating and manipulating ArkTS objects, managing references to and lifecycle of the ArkTS objects, and registering garbage collection (GC) callbacks in C/C++. Before you get started, you need to understand the following concepts:
16
17- Scope: used to ensure that the objects created within a certain scope remain active and are properly cleared when no longer required. Node-API provides APIs for creating and closing normal and escapable scopes.
18- Reference management: Node-API provides APIs for creating, deleting, and managing object references to extend the lifecycle of objects and prevent the use-after-free issues. In addition, reference management also helps prevent memory leaks.
19- Escapable scope: used to return the values created within the **escapable_handle_scope** to a parent scope. It is created by **napi_open_escapable_handle_scope** and closed by **napi_close_escapable_handle_scope**.
20- GC callback: You can register GC callbacks to perform specific cleanup operations when ArkTS objects are garbage-collected.
21
22Understanding these concepts helps you securely and effectively manipulate ArkTS objects in C/C++ and perform object lifecycle management.
23
24## Available APIs
25
26The following table lists the APIs for ArkTS object lifecycle management.
27| API| Description|
28| -------- | -------- |
29| napi_open_handle_scope | Opens a scope.<br/>When processing ArkTS objects with Node-API, you need to create a temporary scope to store object references so that the objects can be correctly accessed during the execution and closed after the execution. |
30| napi_close_handle_scope | Closes a scope. |
31| napi_open_escapable_handle_scope | Opens a scope from which one object can be prompted to the outer scope. |
32| napi_close_escapable_handle_scope | Closes an escapable handle scope. |
33| napi_escape_handle | Promotes the handle to an ArkTS object so that it is valid for the lifetime of its parent scope.|
34| napi_create_reference | Creates a reference to a value to extend the ArkTS object's lifespan. |
35| napi_delete_reference | Deletes a reference. |
36| napi_reference_ref | Increments the reference count. |
37| napi_reference_unref | Decrements the reference count. |
38| napi_get_reference_value | Obtains the ArkTS object associated with the reference.|
39| napi_add_finalizer | Adds a **napi_finalize** callback, which will be called to clean up or release resources before the ArkTS object is garbage-collected.|
40
41## Example
42
43If you are just starting out with Node-API, see [Node-API Development Process](use-napi-process.md). The following demonstrates only the C++ and ArkTS code related to lifecycle management.
44
45### napi_open_handle_scope and napi_close_handle_scope
46
47Use **napi_open_handle_scope** to open a scope, and use **napi_close_handle_scope** to close it. You can use these two APIs to manage the **napi_value** lifecycle of an ArkTS object, which prevents the object from being incorrectly garbage-collected.
48
49Properly using these two APIs can minimize lifecycle and prevent memory leaks.
50
51For details about the code, see [Lifecycle Management](napi-guidelines.md#lifecycle-management).
52
53CPP code:
54
55```cpp
56#include "napi/native_api.h"
57
58static napi_value HandleScopeTest(napi_env env, napi_callback_info info)
59{
60    // Call napi_open_handle_scope to open a scope.
61    napi_handle_scope scope;
62    napi_open_handle_scope(env, &scope);
63    // Create an object within the scope.
64    napi_value obj = nullptr;
65    napi_create_object(env, &obj);
66    // Add a property to the object.
67    napi_value value = nullptr;
68    napi_create_string_utf8(env, "handleScope", NAPI_AUTO_LENGTH, &value);
69    napi_set_named_property(env, obj, "key", value);
70    // Obtain the object property in the scope and return it.
71    napi_value result = nullptr;
72    napi_get_named_property(env, obj, "key", &result);
73    // Close the scope. Then, the object handle created within the scope is automatically released.
74    napi_close_handle_scope(env, scope);
75    // The value of result is 'handleScope'.
76    return result;
77}
78
79static napi_value HandleScope(napi_env env, napi_callback_info info)
80{
81    // Call napi_open_handle_scope to open a scope.
82    napi_handle_scope scope;
83    napi_open_handle_scope(env, &scope);
84    // Create an object within the scope.
85    napi_value obj = nullptr;
86    napi_create_object(env, &obj);
87    // Add a property to the object.
88    napi_value value = nullptr;
89    napi_create_string_utf8(env, "handleScope", NAPI_AUTO_LENGTH, &value);
90    napi_set_named_property(env, obj, "key", value);
91    // Close the scope. Then, the object handle created within the scope is automatically released.
92    napi_close_handle_scope(env, scope);
93    // Obtain and return the object property outside the scope. In this example, "undefined" is obtained.
94    napi_value result = nullptr;
95    napi_get_named_property(env, obj, "key", &result);
96    return result;
97}
98```
99
100API declaration:
101
102```ts
103// index.d.ts
104export const handleScopeTest: () => string;
105export const handleScope: () => string;
106```
107
108ArkTS code:
109
110```ts
111import hilog from '@ohos.hilog'
112import testNapi from 'libentry.so'
113try {
114  hilog.info(0x0000, 'testTag', 'Test Node-API handleScopeTest: %{public}s', testNapi.handleScopeTest());
115  hilog.info(0x0000, 'testTag', 'Test Node-API handleScope: %{public}s', testNapi.handleScope());
116} catch (error) {
117  hilog.error(0x0000, 'testTag', 'Test Node-API handleScopeTest errorCode: %{public}s, errorMessage: %{public}s', error.code, error.message);
118}
119```
120
121### napi_open_escapable_handle_scope, napi_close_escapable_handle_scope, and napi_escape_handle
122
123Use **napi_open_escapable_handle_scope** to open an escapable scope, which allows the declared values in the scope to be returned to the parent scope. You can use **napi_close_escapable_handle_scope** to close it.
124
125Use **napi_escape_handle** to promote the lifecycle of an ArkTS object so that it is valid for the lifetime of the parent scope.
126
127These APIs are helpful for managing ArkTS objects more flexibly in C/C++, especially when passing cross-scope values.
128
129CPP code:
130
131```cpp
132#include "napi/native_api.h"
133
134static napi_value EscapableHandleScopeTest(napi_env env, napi_callback_info info)
135{
136    // Create an escapable scope.
137    napi_escapable_handle_scope scope;
138    napi_open_escapable_handle_scope(env, &scope);
139    // Create an object within the escapable scope.
140    napi_value obj = nullptr;
141    napi_create_object(env, &obj);
142    // Add a property to the object.
143    napi_value value = nullptr;
144    napi_create_string_utf8(env, "Test napi_escapable_handle_scope", NAPI_AUTO_LENGTH, &value);
145    napi_set_named_property(env, obj, "key", value);
146    // Call napi_escape_handle to promote the ArkTS object handle to make it valid with the lifetime of the outer scope.
147    napi_value escapedObj = nullptr;
148    napi_escape_handle(env, scope, obj, &escapedObj);
149    // Close the escapable scope to clear resources.
150    napi_close_escapable_handle_scope(env, scope);
151    // Obtain and return the property of the object whose scope is promoted. You can also obtain napi_escapable_handle_scope here.
152    napi_value result = nullptr;
153    // To verify the escape implementation, obtain the object property here. "undefined" is obtained.
154    napi_get_named_property(env, escapedObj, "key", &result);
155    return result;
156}
157```
158
159API declaration:
160
161```ts
162// index.d.ts
163export const escapableHandleScopeTest: () => string;
164```
165
166ArkTS code:
167
168```ts
169import hilog from '@ohos.hilog'
170import testNapi from 'libentry.so'
171try {
172  hilog.info(0x0000, 'testTag', 'Test Node-API EscapableHandleScopeTest: %{public}s', testNapi.escapableHandleScopeTest());
173} catch (error) {
174  hilog.error(0x0000, 'testTag', 'Test Node-API EscapableHandleScopeTest errorCode: %{public}s, errorMessage: %{public}s', error.code, error.message);
175}
176```
177
178### napi_create_reference and napi_delete_reference
179
180Use **napi_create_reference** to create a reference for an object to extend its lifespan. The caller needs to manage the reference lifespan. Use **napi_delete_reference** to delete a reference.
181
182### napi_reference_ref and napi_reference_unref
183
184Use **napi_reference_ref** to increment the reference count and use **napi_reference_unref** to decrement the reference count, and return the new count value.
185
186### napi_get_reference_value
187
188Use **napi_get_reference_value** to obtain the ArkTS object associated with the reference.
189
190> **NOTE**
191>
192> The release of a weak reference (**napi_ref** whose reference count is 0) and GC of a JS object do not occur at the same time. Consequently, the JS object may be garbage-collected before the weak reference is released. As a result, calling this API may yield a null pointer even if **napi_ref** is valid.
193>
194
195### napi_add_finalizer
196
197Use **napi_add_finalizer** to add a **napi_finalizer** callback, which will be called when the ArkTS object is garbage-collected.
198
199CPP code:
200
201```cpp
202// log.h is used to print logs in C++.
203#include "hilog/log.h"
204#include "napi/native_api.h"
205// Create a pointer to napi_ref to store the created reference. Before calling napi_create_reference, you need to allocate a variable of the napi_ref type and pass its address to the parameter in result.
206napi_ref g_ref;
207
208void Finalizer(napi_env env, void *data, void *hint)
209{
210    // Clear resources.
211    OH_LOG_INFO(LOG_APP, "Node-API: Use terminators to release resources.");
212}
213
214static napi_value CreateReference(napi_env env, napi_callback_info info)
215{
216    napi_value obj = nullptr;
217    napi_create_object(env, &obj);
218    napi_value value = nullptr;
219    napi_create_string_utf8(env, "CreateReference", NAPI_AUTO_LENGTH, &value);
220    // Add a property to the object.
221    napi_set_named_property(env, obj, "key", value);
222    // Create a reference to the ArkTS object.
223    napi_status status = napi_create_reference(env, obj, 1, &g_ref);
224    if (status != napi_ok) {
225        napi_throw_error(env, nullptr, "napi_create_reference fail");
226        return nullptr;
227    }
228    // Add a terminator.
229    void *data = {};
230    napi_add_finalizer(env, obj, data, Finalizer, nullptr, &g_ref);
231    // Increment the reference count and return the new reference count.
232    uint32_t result = 0;
233    napi_reference_ref(env, g_ref, &result);
234    OH_LOG_INFO(LOG_APP, "napi_reference_ref, count = %{public}d.", result);
235    if (result != 2) {
236        // If the reference count passed in does not increase, throw an error.
237        napi_throw_error(env, nullptr, "napi_reference_ref fail");
238        return nullptr;
239    }
240    return obj;
241}
242
243static napi_value UseReference(napi_env env, napi_callback_info info)
244{
245    napi_value obj = nullptr;
246    // Call napi_get_reference_value to obtain the referenced ArkTS object.
247    napi_status status = napi_get_reference_value(env, g_ref, &obj);
248    if (status != napi_ok) {
249        napi_throw_error(env, nullptr, "napi_get_reference_value fail");
250        return nullptr;
251    }
252    // Return the obtained object.
253    return obj;
254}
255
256static napi_value DeleteReference(napi_env env, napi_callback_info info)
257{
258    // Decrement the reference count and return the new reference count.
259    uint32_t result = 0;
260    napi_value count = nullptr;
261    napi_reference_unref(env, g_ref, &result);
262    OH_LOG_INFO(LOG_APP, "napi_reference_ref, count = %{public}d.", result);
263    if (result != 1) {
264        // If the reference count passed in does not decrease, throw an error.
265        napi_throw_error(env, nullptr, "napi_reference_unref fail");
266        return nullptr;
267    }
268    // Call napi_delete_reference to delete the reference to the ArkTS object.
269    napi_status status = napi_delete_reference(env, g_ref);
270    if (status != napi_ok) {
271        napi_throw_error(env, nullptr, "napi_delete_reference fail");
272        return nullptr;
273    }
274    napi_value returnResult = nullptr;
275    napi_create_string_utf8(env, "napi_delete_reference success", NAPI_AUTO_LENGTH, &returnResult);
276    return returnResult;
277}
278```
279
280API declaration:
281
282```ts
283// index.d.ts
284export const createReference: () => Object | void;
285export const useReference: () => Object | void;
286export const deleteReference: () => string | void;
287```
288
289ArkTS code:
290
291```ts
292import hilog from '@ohos.hilog'
293import testNapi from 'libentry.so'
294try {
295  hilog.info(0x0000, 'testTag', 'Test Node-API createReference: %{public}s', JSON.stringify(testNapi.createReference()));
296  hilog.info(0x0000, 'testTag', 'Test Node-API useReference: %{public}s', JSON.stringify(testNapi.useReference()));
297  hilog.info(0x0000, 'testTag', 'Test Node-API deleteReference: %{public}s', testNapi.deleteReference());
298} catch (error) {
299  hilog.error(0x0000, 'testTag', 'Test Node-API ReferenceTest errorCode: %{public}s, errorMessage: %{public}s', error.code, error.message);
300}
301```
302
303To print logs in the native CPP, add the following information to the **CMakeLists.txt** file and add the header file by using **#include "hilog/log.h"**.
304
305```text
306// CMakeLists.txt
307add_definitions( "-DLOG_DOMAIN=0xd0d0" )
308add_definitions( "-DLOG_TAG=\"testTag\"" )
309target_link_libraries(entry PUBLIC libhilog_ndk.z.so)
310```
311