Node-addon-api: Design advice for continuous non-blocking events from N-API addon

Created on 28 Aug 2019  路  3Comments  路  Source: nodejs/node-addon-api

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

All 3 comments

@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:

  • Pass JavaScript function to native function
  • How to pass function exported by core library
  • How to extends function exported by core library by native code

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jeffrson picture jeffrson  路  4Comments

mhdawson picture mhdawson  路  4Comments

rivertam picture rivertam  路  9Comments

bmacnaughton picture bmacnaughton  路  6Comments

D-Andreev picture D-Andreev  路  6Comments