nodejs napi module did not self register

1.4k Views Asked by At

when i try to test nodejs N-API modules, the has a error to me:
my addon.c file is that:

#include <node_api.h>

napi_value HelloMethod (napi_env env, napi_callback_info info) {
  napi_value world;
  napi_create_string_utf8(env, "world", 5, &world);
  return world;
}

void Init (napi_env env, napi_value exports, napi_value module, void* priv) {
  napi_property_descriptor desc = { "hello", 0, HelloMethod, 0, 0, 0, napi_default, 0 };
  napi_define_properties(env, exports, 1, &desc);
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

my binding.gyp file is:

{
  "targets": [
    {
      "target_name": "addon",
      "source": ["addon.c"]
    }
  ]
}

and when i use require('./build/Release/addon') to call addon modules, the error info is :

Error: Module did not self-register.
    at Object.Module._extensions..node (internal/modules/cjs/loader.js:707:18)
    at Module.load (internal/modules/cjs/loader.js:589:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
    at Function.Module._load (internal/modules/cjs/loader.js:520:3)
    at Module.require (internal/modules/cjs/loader.js:626:17)
    at require (internal/modules/cjs/helpers.js:20:18)

has anyone can help me? tanks

2

There are 2 best solutions below

0
On

It seems the newer versions of node-addon-api has changed its API for the module registration/export. The data types that you are using will not work anymore either.

It is now done like so

#include <napi.h>

 Napi::String HelloMethod(const Napi::CallbackInfo& info) {
   Napi::Env env = info.Env();
   return Napi::String::New(env, "world");
 }

 Napi::Object Init(Napi::Env env, Napi::Object exports) {
   exports.Set(Napi::String::New(env, "hello"),
               Napi::Function::New(env, HelloMethod));
   return exports;
 }

NODE_API_MODULE(addon, Init)

This works on node 11.10.1 and node-addon-api 1.6.2.

0
On

Try to change the file name "addon.c" to "addon.cpp", then rebuild and run.

See this: Successful compiling the Node module and "Module did not self-register."