Node.js N-API插件-如何对JSON进行字符串化/解析?

时间:2018-09-06 00:41:48

标签: node.js node.js-addon node.js-napi

我正在使用N-API(C接口,不要与围绕N-API的node-addon-api C ++包装器相混淆)编写Node.js的插件,该插件从JSON格式接收数据。外部源,需要在其对象形式上执行JS回调函数。但是,我迷失了一种将JSON格式的数据解析到插件内适当的对象(即,由JSON.parse生成)的方法,然后再将其传递给JS回调,并且似乎只能在其文本中传递表格。

到目前为止,我发现的唯一做到这一点的示例涉及直接使用C++ NAN和V8 API。我想念什么吗?我是否应该再对JSON.parse进行napi_call_function调用,捕获其返回值,然后将其传递? (如果是这样,我如何从我的插件中获取JSON.parse回调信息?)有没有找到一个更简单的API?

出于许多原因,我宁愿选择使用C而不是C ++,尽管我认为这是可以商量的。

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);
    // ...

1 个答案:

答案 0 :(得分:1)

下面是一个示例,说明如何在C ++而不是Javascript端进行字符串化和解析。 Napi允许您从C ++代码调用javascript函数。以下是如何调用JSON.stringify()JSON.parse()

的示例
Napi::String JSONStringify(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  Napi::Object json_object = info[0].As<Napi::Object>();
  Napi::Object json = env.Global().Get("JSON").As<Napi::Object>();
  Napi::Function stringify = json.Get("stringify").As<Napi::Function>();
  return stringify.Call(json, { json_object }).As<Napi::String>();
}

Napi::Object JSONParse(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  Napi::String json_string = info[0].As<Napi::String>();
  Napi::Object json = env.Global().Get("JSON").As<Napi::Object>();
  Napi::Function parse = json.Get("parse").As<Napi::Function>();
  return parse.Call(json, { json_string }).As<Napi::Object>();
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
  exports["jsonStringify"] =  Napi::Function::New(env, JSONStringify);
  exports["jsonParse"] = Napi::Function::New(env, JSONParse);          
  return exports;
}

NODE_API_MODULE(json, Init)

来源:https://github.com/nodejs/node-addon-api/issues/410#issuecomment-574876170

相关问题