Hello,
I am just getting started with N-API, and could use some design advice.
I have some C++ code that opens a Linux socket and receives a continuous stream of async data.
I want to integrate that code in an N-API addon that I can instantiate and control from Node.js.
I have this simple N-API addon EventEmitter code running:
https://github.com/NickNaso/addon-event-emitter
but it blocks JavaScript when Node.js calls the N-API exported function that causes the C++ event emitter to run:
emitter.callAndEmit()
I assume that happens because the C++ code is running on the same thread as the JavaScript engine. (As soon as the addon callAndEmit() function completes, JavaScript resumes execution.)
I experimented with using Node worker_threads to run that same N-API code in a worker thread the communicates results back to the parent thread, and that seems to work.
But is that a good design, or a clumsy hack?
What is the best way to structure a Node app that interacts with continuously running N-API C++ code such that it can receive async events without blocking the main JavaScript thread?
Thanks!
Jim
@jfathman if you are using threads and you need to call into JS from another thread, try Napi::ThreadSafeFunction.
Hi @jfathman,
I implemented the library that you used for a talk and a workshop that I did to explain some concepts:
You're right it blocks the execution and I agree with @gabrielschulhof that the right choice for your case could be Napi::ThreadSafeFunction.
Hi @gabrielschulhof and @NickNaso,
Thanks for your good advice. I got some Napi::ThreadSafeFunction hello world code running today, and it looks like just the architecture I need.
Really appreciate your work on this excellent API, and your willingness to quickly respond to questions from the community.
Jim