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