Search code examples
node.jsnode.js-addonn-api

How do I save a callback for later with node-addon-api?


I want my C library to be able to call a JS function multiple times. I got it to work using Nan but am having trouble converting it to N-API/node-addon-api.

How do I save a JS callback function and call it later from C?

Here's what I have using Nan:

Persistent<Function> r_log;
void sendLogMessageToJS(char* msg) {
    if (!r_log.IsEmpty()) {
        Isolate* isolate = Isolate::GetCurrent();
        Local<Function> func = Local<Function>::New(isolate, r_log);
        if (!func.IsEmpty()) {
        const unsigned argc = 1;
        Local<Value> argv[argc] = {
            String::NewFromUtf8(isolate, msg)
        };
        func->Call(Null(isolate), argc, argv);
        }
    }
}
NAN_METHOD(register_logger) {
    Isolate* isolate = info.GetIsolate();
    if (info[0]->IsFunction()) {
        Local<Function> func = Local<Function>::Cast(info[0]);
        Function * ptr = *func;
        r_log.Reset(isolate, func);
        myclibrary_register_logger(sendLogMessageToJS);
    } else {
        r_log.Reset();
    }
}

How do I do the equivalent with node-addon-api? All the examples I've seen immediately call the callback or use AsyncWorker to somehow save the callback. I can't figure out how AsyncWorker is doing it.


Solution

  • I got an answer from the node-addon-api maintainers which led me to this solution:

    FunctionReference r_log;
    void emitLogInJS(char* msg) {
      if (r_log != nullptr) {
        const Env env = r_log.Env();
        const String message = String::New(env, msg);
        const std::vector<napi_value> args = {message}; 
        r_log.Call(args);
      } 
    }
    void register_logger(const CallbackInfo& info) {
      r_log = Persistent(info[0].As<Function>());
      myclibrary_register_logger(emitLogInJS);
    }