node-cpp-modules
node-cpp-modules copied to clipboard
why no v8 code in AsyncWork
I have some work to do in AsyncWork, like transforming c struct into v8::Object. So I have to write v8 code in AsyncWork. How can I manage this?
just to use callback function,like this: // addon.cc #include <node.h>
namespace demo {
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<Function> cb = Local<Function>::Cast(args[0]); const unsigned argc = 1; Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") }; cb->Call(Null(isolate), argc, argv); }
void Init(Local<Object> exports, Local<Object> module) { NODE_SET_METHOD(module, "exports", RunCallback); }
NODE_MODULE(addon, Init)
} // namespace demo Note that 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.
To test it, run the following JavaScript:
// test.js const addon = require('./build/Release/addon');
addon((msg) => { console.log(msg); // 'hello world' }); Note that, in this example, the callback function is invoked synchronously.