-1

Edit: apparently it's not clear, guess I'll make it more concise.

Node application is built, uses a native addon. I need to pass in a Javascript function from this project through node-addon-api into my C++ addon. Then, I need to be able to call that function from C++ multiple times. The issue arose when I found out I am unable to save the reference to the Javascript function due to the napi_env (required for calling the function) being protected from caching.

Could not find any clear answers or examples on the internet regarding how to do this, looking for tips.

Original:

as the title describes, I need to figure out a way to call a JS function multiple times in my addon. Generic use case is that my addon does some long running commands and needs to periodically push a status update back to the javascript.

I thought the best approach would be to have the user pass in a function (which just appends to a text block) for my addon to call (so it can write the updates), this way the javascript side can decide where it gets displayed.

I have experimented to get this working. Found out that my original way of saving the function in a persistent napi_value doesn't work since you cannot save napi_env as well.

I found this thread, which I think is the closest to what I need, but I can't manage to translate the Nan to napi_ so it would work with what I'm using. Callback NodeJS Javascript function from multithreaded C++ addon

Also attempted passing in an EventEmitter, but similar problem as above.

Can anyone give some pointers on if I am heading in the right direction? Perhaps help me dig up a few examples on how to accomplish this?

Yang Lu
  • 3
  • 4

1 Answers1

0

Your question is not clear. Assuming you are using Javascript in Node, have a look at FFI which allows one to loading and calling dynamic libraries using Javascript.

Alternatively one can just execute a function as follows from the command line:

/usr/bin/node yourjsfunctionfilehere.js

You can also pass command line parameters to the called JS function.

TrevTheDev
  • 2,616
  • 2
  • 18
  • 36
  • Have you looked at [child processes](https://nodejs.org/api/child_process.html#child_process_subprocess_stdin) it can be used to send messages between different processes? – TrevTheDev Mar 14 '19 at 01:04