在 Node.js 环境退出时完成


【Finalization on the exit of the Node.js environment】

Node.js 环境可能会在任意时间尽快被拆除,并且不允许执行 JavaScript,例如应 worker.terminate() 的请求。当环境正在被拆除时,JavaScript 对象、线程安全函数和环境实例数据的已注册 napi_finalize 回调会立即且独立地被调用。

【The Node.js environment may be torn down at an arbitrary time as soon as possible with JavaScript execution disallowed, like on the request of worker.terminate(). When the environment is being torn down, the registered napi_finalize callbacks of JavaScript objects, thread-safe functions and environment instance data are invoked immediately and independently.】

napi_finalize 回调的调用会在手动注册的清理钩子之后进行调度。为了在环境关闭期间确保插件最终化的正确顺序,从而避免在 napi_finalize 回调中出现使用已释放资源的情况,插件应使用 napi_add_env_cleanup_hooknapi_add_async_cleanup_hook 注册清理钩子,以按正确顺序手动释放分配的资源。

【The invocation of napi_finalize callbacks is scheduled after the manually registered cleanup hooks. In order to ensure a proper order of addon finalization during environment shutdown to avoid use-after-free in the napi_finalize callback, addons should register a cleanup hook with napi_add_env_cleanup_hook and napi_add_async_cleanup_hook to manually release the allocated resource in a proper order.】