环境生命周期 API
¥Environment life cycle APIs
ECMAScript 语言规范 的 第 8.7 节 将 "代理" 的概念定义为运行 JavaScript 代码的独立环境。进程可以同时或按顺序启动和终止多个此类代理。
¥Section 8.7 of the ECMAScript Language Specification defines the concept of an "Agent" as a self-contained environment in which JavaScript code runs. Multiple such Agents may be started and terminated either concurrently or in sequence by the process.
一个 Node.js 环境对应一个 ECMAScript Agent。在主进程中,启动时创建一个环境,可以在单独的线程上创建额外的环境作为 工作线程。当 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.
原生插件可能需要分配它们在整个生命周期中使用的全局状态,以便该状态对于插件的每个实例都必须是唯一的。
¥Native addons may need to allocate global state which they use during their entire life cycle such that the state must be unique to each instance of the addon.
为此,Node-API 提供了一种分配数据的方法,使其生命周期与代理的生命周期相关联。
¥To this end, Node-API provides a way to allocate data such that its life cycle is tied to the life cycle of the Agent.