环境生命周期 API


【Environment life cycle APIs】

ECMAScript 语言规范代理部分 将“代理”的概念定义为一个独立的环境,在其中运行 JavaScript 代码。多个这样的代理可以由进程同时或按顺序启动和终止。

Node.js 环境对应于 ECMAScript 代理。在主进程中,环境在启动时被创建,并且可以在单独的线程上创建额外的环境以作为 工作线程。当 Node.js 被嵌入到其他应用中时,应用的主线程在应用进程的生命周期内可能会多次构建和销毁 Node.js 环境,因此应用创建的每个 Node.js 环境在其生命周期内也可能创建和销毁额外的环境作为工作线程。

【A Node.js environment corresponds to an ECMAScript Agent. In the main process, an environment is created at startup, and additional environments can be created on separate threads to serve as worker threads. When Node.js is embedded in another application, the main thread of the application may also construct and destroy a Node.js environment multiple times during the life cycle of the application process such that each Node.js environment created by the application may, in turn, during its life cycle create and destroy additional environments as worker threads.】

从本地插件的角度来看,这意味着它提供的绑定可能会被多次调用,来自多个上下文,甚至可能同时来自多个线程。

【From the perspective of a native addon this means that the bindings it provides may be called multiple times, from multiple contexts, and even concurrently from multiple threads.】

本地插件可能需要分配全局状态,以便在 Node.js 环境的生命周期中使用该状态,从而使每个插件实例的状态都是唯一的。

【Native addons may need to allocate global state which they use during their life cycle of an Node.js environment such that the state can be unique to each instance of the addon.】

为此,Node-API 提供了一种方式来关联数据,使其生命周期与 Node.js 环境的生命周期相关联。

【To this end, Node-API provides a way to associate data such that its life cycle is tied to the life cycle of a Node.js environment.】