Search code examples
c++node.jsnode-modulesnode.js-addonnode-addon-api

Addons: TypeError: addons.function() is not a function


I'm still new into addons and such. I'm trying to run a simple c++ function that prints "Hello MIKE" into node js. However, I get this following error:

TypeError: addons.greetHello is not a function
    at Object.<anonymous> (F:\addons\index.js:6:46)
    at Module._compile (internal/modules/cjs/loader.js:1147:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

that's my main cpp

#include<napi.h>
#include <string>
#include "greeting.h"



Napi::String greetHello(const Napi::CallbackInfo& info)
{
    Napi::Env env = info.Env();
    std::string result = helloUser("Mike");
    return Napi::String::New(env ,result);
}
Napi::Object Init(Napi::Env env , Napi::Object exports)
{
    exports.Set
    (
        Napi::String::New(env, "Function"),
        Napi::Function::New(env, greetHello)
    );
    return exports;
}

NODE_API_MODULE(addons, Init)



and my index.js

const addons = require('./build/Release/addons.node');

console.log('exports : ' , addons);
console.log();

console.log('addons.greetHello() : ', addons.greetHello() );
console.log();

Also there something I noticed that wasn't the same as the tutorial I'm following. here that's the function I take from my main cpp: exports : { Function: [Function (anonymous)] } In the tutorial there wasn't that anonymous part, so why does it read mine as anonymous here?

Thanks in advance


Solution

  • Your current invocation will assign the function to the "Function" export, you probably wanted "greetHello". For your other question, you can pass a name to Napi::Function::New:

    exports.Set
    (
        Napi::String::New(env, "greetHello"),
        Napi::Function::New(env, greetHello, "greetHello")
    );