1# Working with Cleanup Hooks Using Node-API 2 3## Introduction 4 5Node-API provides APIs for adding and removing cleanup hooks, which are called to release resources when the environment exits. 6 7## Basic Concepts 8 9Before using Node-API to add or remove cleanup hooks, understand the following concepts: 10 11- Resource management<br>In ArkTS, you need to manage system resources, such as memory, file handles, and network connections. Properly creating, using, and releasing these resources during the lifecycle of the Node-API module can prevent resource leaks and application breakdown. Resource management usually includes initializing resources, clearing resources when required, and performing necessary operations when clearing resources, such as closing a file or disconnecting from the network. 12- Hook function<br>A hook function is a callback that is automatically executed at the specified time or upon a specific event. When an environment or a process exits, not all the resources can be automatically reclaimed immediately. In the context of a Node-API module, the cleanup hooks are a supplement that ensures release of all the resources occupied. 13 14So far, you've learnt resource management in ArkTS and cleanup hook functions. Read on to learn the Node-API interfaces that you can use to perform resource management with cleanup hooks. 15 16## Available APIs 17 18The following table lists the APIs for using different types of cleanup hooks. 19 20| API| Description| 21| -------- | -------- | 22| napi_add_env_cleanup_hook | Adds an environment cleanup hook function, which will be called when the Node-API environment exits.| 23| napi_remove_env_cleanup_hook | Removes an environment cleanup hook function.| 24| napi_add_async_cleanup_hook | Adds an async cleanup hook function, which will be executed asynchronously when the Node-API process exits.| 25| napi_remove_async_cleanup_hook | Removes an async cleanup hook function.| 26 27## Example 28 29If 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 involved in the APIs for cleanup hooks. 30 31### napi_add_env_cleanup_hook 32 33Call **napi_add_env_cleanup_hook** to add an environment cleanup hook function, which will be executed when the environment exits. This ensures that resources are released before the environment is destroyed. 34 35 36### napi_remove_env_cleanup_hook 37 38Call **napi_remove_env_cleanup_hook** to remove the previously added environment cleanup hook function. You may need to use this API when an addon is uninstalled or resources are reallocated. 39 40CPP code: 41 42```cpp 43#include <hilog/log.h> 44#include <string> 45#include "napi/native_api.h" 46// Define the memory struct, including the pointer to the data and the data size. 47typedef struct { 48 char *data; 49 size_t size; 50} Memory; 51// Callback for clearing the external buffer. It is used to release the allocated memory. 52void ExternalFinalize(napi_env env, void *finalize_data, void *finalize_hint) 53{ 54 Memory *wrapper = (Memory *)finalize_hint; 55 free(wrapper->data); 56 free(wrapper); 57 OH_LOG_INFO(LOG_APP, "Node-API napi_add_env_cleanup_hook ExternalFinalize"); 58} 59// Perform cleanup operations when the environment is closed, for example, clear global variables or other resources. 60static void Cleanup(void *arg) 61{ 62 // Perform the cleanup operation. 63 OH_LOG_INFO(LOG_APP, "Node-API napi_add_env_cleanup_hook cleanuped: %{public}d", *(int *)(arg)); 64} 65// Create an external buffer and add the environment cleanup hook function. 66static napi_value NapiEnvCleanUpHook(napi_env env, napi_callback_info info) 67{ 68 // Allocate memory and copy the string to the memory. 69 std::string str("Hello from Node-API!"); 70 Memory *wrapper = (Memory *)malloc(sizeof(Memory)); 71 wrapper->data = (char *)malloc(str.size()); 72 strcpy(wrapper->data, str.c_str()); 73 wrapper->size = str.size(); 74 // Create an external buffer object and specify the cleanup callback function. 75 napi_value buffer = nullptr; 76 napi_create_external_buffer(env, wrapper->size, (void *)wrapper->data, ExternalFinalize, wrapper, &buffer); 77 // Use static variables as hook function parameters. 78 static int hookArg = 42; 79 static int hookParameter = 1; 80 // Add a cleanup hook function for releasing resources when the environment exits. 81 napi_status status = napi_add_env_cleanup_hook(env, Cleanup, &hookArg); 82 if (status != napi_ok) { 83 napi_throw_error(env, nullptr, "Test Node-API napi_add_env_cleanup_hook failed."); 84 return nullptr; 85 } 86 // Add the environment cleanup hook function. The hook function is not removed here to make it called to simulate some cleanup operations, such as releasing resources and closing files, when the Java environment is destroyed. 87 status = napi_add_env_cleanup_hook(env, Cleanup, &hookParameter); 88 if (status != napi_ok) { 89 napi_throw_error(env, nullptr, "Test Node-API napi_add_env_cleanup_hook failed."); 90 return nullptr; 91 } 92 // Remove the environment cleanup hook function immediately. 93 // Generally, use this API when the resource associated with the hook must be released. 94 napi_remove_env_cleanup_hook(env, Cleanup, &hookArg); 95 // Return the created external buffer object. 96 return buffer; 97} 98``` 99 100API declaration: 101 102```ts 103// index.d.ts 104export const napiEnvCleanUpHook: () => Object | void; 105``` 106 107ArkTS code: 108 109```ts 110// index.ets 111import hilog from '@ohos.hilog' 112import worker from '@ohos.worker' 113 114let wk = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 115// Send a message to the worker thread. 116wk.postMessage("test NapiEnvCleanUpHook"); 117// Process the message from the worker thread. 118wk.onmessage = (message) => { 119 hilog.info(0x0000, 'testTag', 'Test Node-API message from worker: %{public}s', JSON.stringify(message)); 120 wk.terminate(); 121}; 122``` 123 124```ts 125// worker.ts 126import hilog from '@ohos.hilog' 127import worker from '@ohos.worker' 128import testNapi from 'libentry.so' 129 130let parent = worker.workerPort; 131// Process messages from the main thread. 132parent.onmessage = function(message) { 133 hilog.info(0x0000, 'testTag', 'Test Node-API message from main thread: %{public}s', JSON.stringify(message)); 134 // Send a message to the main thread. 135 parent.postMessage('Test Node-API worker:' + testNapi.napiEnvCleanUpHook()); 136} 137``` 138 139For details about the worker development, see [Worker Introduction](../arkts-utils/worker-introduction.md). 140 141### napi_add_async_cleanup_hook 142 143Call **napi_add_async_cleanup_hook** to add an async cleanup hook function, which will be executed asynchronously when the environment exits. Unlike a sync hook, an async hook allows a longer operation without blocking the process exit. 144 145### napi_remove_async_cleanup_hook 146 147Call **napi_remove_async_cleanup_hook** to remove an async cleanup hook function that is no longer required. 148 149CPP code: 150 151```cpp 152#include <malloc.h> 153#include <string.h> 154#include "napi/native_api.h" 155#include "uv.h" 156 157// Async operation content. 158typedef struct { 159 napi_env env; 160 void *testData; 161 uv_async_s asyncUv; 162 napi_async_cleanup_hook_handle cleanupHandle; 163} AsyncContent; 164// Delete the async work object and remove the hook function. 165static void FinalizeWork(uv_handle_s *handle) 166{ 167 AsyncContent *asyncData = reinterpret_cast<AsyncContent *>(handle->data); 168 // Remove the hook function from the environment when it is no longer required. 169 napi_status result = napi_remove_async_cleanup_hook(asyncData->cleanupHandle); 170 if (result != napi_ok) { 171 napi_throw_error(asyncData->env, nullptr, "Test Node-API napi_remove_async_cleanup_hook failed"); 172 } 173 // Release AsyncContent. 174 free(asyncData); 175} 176// Asynchronously clear the environment. 177static void AsyncWork(uv_async_s *async) 178{ 179 // Perform cleanup operations, for example, release the dynamically allocated memory. 180 AsyncContent *asyncData = reinterpret_cast<AsyncContent *>(async->data); 181 if (asyncData->testData != nullptr) { 182 free(asyncData->testData); 183 asyncData->testData = nullptr; 184 } 185 // Close the libuv handle and trigger the FinalizeWork callback to clear the handle. 186 uv_close((uv_handle_s *)async, FinalizeWork); 187} 188// Create and trigger an async cleanup operation in an event loop. 189static void AsyncCleanup(napi_async_cleanup_hook_handle handle, void *info) 190{ 191 AsyncContent *data = reinterpret_cast<AsyncContent *>(info); 192 // Obtain a libuv loop instance and initialize a handle for subsequent async work. 193 uv_loop_s *uvLoop; 194 napi_get_uv_event_loop(data->env, &uvLoop); 195 uv_async_init(uvLoop, &data->asyncUv, AsyncWork); 196 197 data->asyncUv.data = data; 198 data->cleanupHandle = handle; 199 // Send an async signal to trigger the AsyncWork function to perform cleanup. 200 uv_async_send(&data->asyncUv); 201} 202 203static napi_value NapiAsyncCleanUpHook(napi_env env, napi_callback_info info) 204{ 205 // Allocate the AsyncContent memory. 206 AsyncContent *data = reinterpret_cast<AsyncContent *>(malloc(sizeof(AsyncContent))); 207 data->env = env; 208 data->cleanupHandle = nullptr; 209 // Allocate memory and copy string data. 210 const char *testDataStr = "TestNapiAsyncCleanUpHook"; 211 data->testData = strdup(testDataStr); 212 if (data->testData == nullptr) { 213 napi_throw_error(env, nullptr, "Test Node-API data->testData is nullptr"); 214 } 215 // Add an async cleanup hook function. 216 napi_status status = napi_add_async_cleanup_hook(env, AsyncCleanup, data, &data->cleanupHandle); 217 if (status != napi_ok) { 218 napi_throw_error(env, nullptr, "Test Node-API napi_add_async_cleanup_hook failed"); 219 } 220 napi_value result = nullptr; 221 napi_get_boolean(env, true, &result); 222 return result; 223} 224``` 225 226Since the uv.h library is used, add the following configuration to the CMakeLists file: 227```text 228// CMakeLists.txt 229target_link_libraries(entry PUBLIC libuv.so) 230``` 231 232API declaration: 233 234```ts 235// index.d.ts 236export const napiAsyncCleanUpHook: () => boolean | void; 237``` 238 239ArkTS code: 240 241```ts 242import hilog from '@ohos.hilog' 243import testNapi from 'libentry.so' 244try { 245 hilog.info(0x0000, 'testTag', 'Test Node-API napi_add_async_cleanup_hook: %{public}s', testNapi.napiAsyncCleanUpHook()); 246} catch (error) { 247 hilog.error(0x0000, 'testTag', 'Test Node-API napi_add_async_cleanup_hook error.message: %{public}s', error.message); 248} 249``` 250 251To 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"**. 252 253```text 254// CMakeLists.txt 255add_definitions( "-DLOG_DOMAIN=0xd0d0" ) 256add_definitions( "-DLOG_TAG=\"testTag\"" ) 257target_link_libraries(entry PUBLIC libhilog_ndk.z.so) 258``` 259