I am building a C++ addon for NodeJS and I want to stream data asynchronously from C++ to Node. I have found this article, https://nodeaddons.com/streaming-data-into-a-node-js-c-addon/, however; I want to use the N-API instead of NAN.
I have been searching through the NodeJS docs and examples as well as looking for other resources and examples but have not come across a resource to show me how I can accomplish this. This is my first time writing a C++ addon for NodeJS.
An example that would help me get started would be an addon that uses the N-API to send a dummy string every second to Node and Node would print the string to the console.
Here is a snippet based on EventEmitter concept, which simulates reading of sensors from native layer (C/C++) and push the data to Node.js (JavaScript) layer. In this example we are using node-addon-api, a header-only C++ wrapper to N-API. Here for this example we have used a for loop (with only five iteratins), in reality it could be an infinite loop continuously reading sensors outputs and pushing the data to JS layer. The native layer can decide when to report the data it got collected from sensors to the JS layer. The JS will receive the data asynchronous for the subscribed events.
The module registration snippet is
Compile the above native code and once it is successfully built then you can run the following node.js JavaScript code to test it.
The code snippet should produce the following output.