回调
【Callbacks】
在插件中,将 JavaScript 函数传递给 C++ 函数并从那里执行是常见的做法。下面的示例说明了如何调用此类回调:
【It is common practice within addons to pass JavaScript functions to a C++ function and execute them from there. The following example illustrates how to invoke such callbacks:】
// addon.cc
#include <node.h>
namespace demo {
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Null;
using v8::Object;
using v8::String;
using v8::Value;
void RunCallback(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<Function> cb = Local<Function>::Cast(args[0]);
const unsigned argc = 1;
Local<Value> argv[argc] = {
String::NewFromUtf8(isolate,
"hello world").ToLocalChecked() };
cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
}
void Init(Local<Object> exports, Local<Object> module) {
NODE_SET_METHOD(module, "exports", RunCallback);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
} // namespace demo 这个示例使用了 Init() 的两参数形式,其第二个参数接收完整的 module 对象。这样,addon 可以用一个单独的函数完全覆盖 exports,而不是将函数作为 exports 的一个属性添加。
【This example uses a two-argument form of Init() that receives the full
module object as the second argument. This allows the addon to completely
overwrite exports with a single function instead of adding the function as a
property of exports.】
要测试它,则运行以下 JavaScript:
【To test it, run the following JavaScript:】
// test.js
const addon = require('./build/Release/addon');
addon((msg) => {
console.log(msg);
// Prints: 'hello world'
}); 在这个例子中,回调函数是同步调用的。
【In this example, the callback function is invoked synchronously.】