上下文感知的插件
【Context-aware addons】
在某些环境中,Node.js 插件可能需要在多个上下文中多次加载。例如,电子 运行时在单个进程中运行多个 Node.js 实例。每个实例都会有自己独立的 require() 缓存,因此每个实例在通过 require() 加载原生插件时都需要插件能够正确运行。这意味着插件必须支持多次初始化。
【There are environments in which Node.js addons may need to be loaded multiple
times in multiple contexts. For example, the Electron runtime runs multiple
instances of Node.js in a single process. Each instance will have its own
require() cache, and thus each instance will need a native addon to behave
correctly when loaded via require(). This means that the addon
must support multiple initializations.】
可以使用宏 NODE_MODULE_INITIALIZER 构建一个上下文感知的插件,该宏会展开为 Node.js 在加载插件时期望找到的函数名。插件因此可以像下面的示例一样进行初始化:
【A context-aware addon can be constructed by using the macro
NODE_MODULE_INITIALIZER, which expands to the name of a function which Node.js
will expect to find when it loads an addon. An addon can thus be initialized as
in the following example:】
using namespace v8;
extern "C" NODE_MODULE_EXPORT void
NODE_MODULE_INITIALIZER(Local<Object> exports,
Local<Value> module,
Local<Context> context) {
/* Perform addon initialization steps here. */
} 另一种选择是使用宏 NODE_MODULE_INIT(),它也会构建一个具有上下文感知的插件。与 NODE_MODULE() 不同,后者用于围绕给定的插件初始化函数构建插件,NODE_MODULE_INIT() 用作此类初始化函数的声明,后面跟随一个函数体。
【Another option is to use the macro NODE_MODULE_INIT(), which will also
construct a context-aware addon. Unlike NODE_MODULE(), which is used to
construct an addon around a given addon initializer function,
NODE_MODULE_INIT() serves as the declaration of such an initializer to be
followed by a function body.】
在调用 `NODE_MODULE_INIT()`` 后,函数体内可以使用以下三个变量:
【The following three variables may be used inside the function body following an
invocation of NODE_MODULE_INIT():】
本地<Object> 导出,Local<Value> 模块,以及Local<Context> context
构建上下文感知的插件需要仔细管理全局静态数据,以确保稳定性和正确性。由于插件可能被多次加载,甚至可能来自不同的线程,因此存储在插件中的任何全局静态数据都必须妥善保护,并且不能包含对 JavaScript 对象的任何持久引用。原因在于,JavaScript 对象仅在一个上下文中有效,如果从错误的上下文或与创建它们的线程不同的线程访问,可能会导致崩溃。
【Building a context-aware addon requires careful management of global static data to ensure stability and correctness. Since the addon may be loaded multiple times, potentially even from different threads, any global static data stored in the addon must be properly protected, and must not contain any persistent references to JavaScript objects. The reason for this is that JavaScript objects are only valid in one context, and will likely cause a crash when accessed from the wrong context or from a different thread than the one on which they were created.】
可以通过执行以下步骤来构建上下文感知插件,从而避免使用全局静态数据:
【The context-aware addon can be structured to avoid global static data by performing the following steps:】
-
定义一个类,它将保存每个插件实例的数据,并且具有以下形式的静态成员
static void DeleteInstance(void* data) { // Cast `data` to an instance of the class and delete it. } -
Heap-allocate an instance of this class in the addon initializer. This can be accomplished using the
newkeyword. -
Call
node::AddEnvironmentCleanupHook(), passing it the above-created instance and a pointer toDeleteInstance(). This will ensure the instance is deleted when the environment is torn down. -
Store the instance of the class in a
v8::External, and -
Pass the
v8::Externalto all methods exposed to JavaScript by passing it tov8::FunctionTemplate::New()orv8::Function::New()which creates the native-backed JavaScript functions. The third parameter ofv8::FunctionTemplate::New()orv8::Function::New()accepts thev8::Externaland makes it available in the native callback using thev8::FunctionCallbackInfo::Data()method.
这将确保每个插件实例的数据能够到达可以从 JavaScript 调用的每个绑定。每个插件实例的数据还必须传递到插件可能创建的任何异步回调中。
【This will ensure that the per-addon-instance data reaches each binding that can be called from JavaScript. The per-addon-instance data must also be passed into any asynchronous callbacks the addon may create.】
以下示例说明了上下文感知插件的实现:
【The following example illustrates the implementation of a context-aware addon:】
#include <node.h>
using namespace v8;
class AddonData {
public:
explicit AddonData(Isolate* isolate):
call_count(0) {
// Ensure this per-addon-instance data is deleted at environment cleanup.
node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);
}
// Per-addon data.
int call_count;
static void DeleteInstance(void* data) {
delete static_cast<AddonData*>(data);
}
};
static void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {
// Retrieve the per-addon-instance data.
AddonData* data =
reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());
data->call_count++;
info.GetReturnValue().Set((double)data->call_count);
}
// Initialize this addon to be context-aware.
NODE_MODULE_INIT(/* exports, module, context */) {
Isolate* isolate = Isolate::GetCurrent();
// Create a new instance of `AddonData` for this instance of the addon and
// tie its life cycle to that of the Node.js environment.
AddonData* data = new AddonData(isolate);
// Wrap the data in a `v8::External` so we can pass it to the method we
// expose.
Local<External> external = External::New(isolate, data);
// Expose the method `Method` to JavaScript, and make sure it receives the
// per-addon-instance data we created above by passing `external` as the
// third parameter to the `FunctionTemplate` constructor.
exports->Set(context,
String::NewFromUtf8(isolate, "method").ToLocalChecked(),
FunctionTemplate::New(isolate, Method, external)
->GetFunction(context).ToLocalChecked()).FromJust();
}