I'm writing an addon for Node.js using N-API (the C interface, not to be confused with the node-addon-api C++ wrapper around N-API) which receives JSON-formatted data from an external source and needs to execute a JS callback function on its object form. However, I'm lost for a way to parse the JSON-formatted data into a proper object (i.e., resulting from JSON.parse) within the addon before passing it into the JS callback and can only seem to pass it on in its text form.
The only examples I've found so far that do this involve using the C++ NAN and V8 APIs directly. Am I missing something? Should I make another napi_call_function call to JSON.parse, capture its return value, then pass that on? (If so, how do I get the JSON.parse callback info from my addon?) Is there a simpler API that I've not found?
For many reasons, I'd prefer to stay in C, not C++, though I suppose that's negotiable.
foo.js
const myaddon = require('bindings')('myaddon');
const EventEmitter = require('events').EventEmitter;
const emitter = new EventEmitter();
emitter.on('eventReceived', (foo) => {
var obj = JSON.parse(foo); // *** this is what I'd like to avoid ***
console.log(obj.bar);
})
myaddon.RegisterForEvents(emitter.emit.bind(emitter));
myaddon.c
void AsyncComplete(napi_env env, napi_status status, void * data) {
// do some work to get the JSON text from the external source,
// setup argv with the necessary values:
// argv[0]: "eventReceived"
// argv[1]: JSON text -- would like to deserialize in addon, not in JS callback, so the JS callback receives a proper object
// Execute the JS function
napi_call_function(env, global /* from napi_get_global */, callback /* the emitter */, argc, argv, NULL);
// ...