I want to write the below code for multiple object initialization for Node Addon. Please let me know what is wrong in below code

  add-on, c++, node-addon-api

I am returning multiple object using one node addon.

#include <napi.h>
#include "myobject.h"
#include "myobject1.h"
#include "myobject2.h"
#include <iostream>
Napi::Object CreateObject(const Napi::CallbackInfo& info) 
{
    int num = info[0].As<Napi::Number>().Int32Value();
    switch (num)
    {
    case 1:
        std::cout << "Object 1" << std::endl;
        return MyObject::NewInstance(info.Env(), info[0]);
        break;
    case 2:
        std::cout << "Object 2" << std::endl;
        return MyObject1::NewInstance(info.Env(), info[0]);
        break;
    case 3:
        std::cout << "Object 3" << std::endl;
        return MyObject2::NewInstance(info.Env(), info[0]);
        break;
    }
  
}

Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
  Napi::Object new_exports = Napi::Function::New(env, CreateObject, "CreateObject");
  return MyObject::Init(env, new_exports);
}

NODE_API_MODULE(addon, InitAll)

The js file which is using above code is like this.

var createObject = require('bindings')('addon');
var obj = createObject(1);
var obj2 = createObject(2);
var obj3 = createObject(3);

addon code is compiled fine, but js is giving below error.
FATAL ERROR: Error::New napi_get_last_error_info
1: 00007FF68F1F046F napi_wrap+109311
2: 00007FF68F195156 v8::internal::OrderedHashTable<v8::internal::OrderedHashMap,2>::NumberOfElementsOffset+33302
3: 00007FF68F195F26 node::OnFatalError+294
4: 00007FF68F1957C9 v8::internal::OrderedHashTable<v8::internal::OrderedHashMap,2>::NumberOfElementsOffset+34953
5: 00007FF68F1BE2EC napi_fatal_error+156
6: 00007FF8677D14E7 public: static void __cdecl Napi::Error::Fatal(char const * __ptr64,char const * __ptr64)+23
7: 00007FF8677D1475 public: static class Napi::Error cdecl Napi::Error::New(struct napi_env * __ptr64)+421
8: 00007FF8677D413C Napi::EscapableHandleScope::EscapableHandleScope+60 [C:Projectabi-stable-node-addon-examples-master_factory_wrapnode-addon-apinode_modulesnode-addon-apinapi-inl.h]:L3445

Source: Windows Questions C++

LEAVE A COMMENT