Why can't N-API find some bindings when using napi_property_descriptor array?

255 Views Asked by At

I have the following code...

// robot_node.c
#include <stdio.h>
#include <string.h>
#include "robot_node.h"
#include "robot.h"

napi_value node_forward(napi_env env, napi_callback_info info){
    napi_value result;
    napi_status status;
    int answer = forward();
    status = napi_create_int64(env, answer, &result);
    if (status != napi_ok) return NULL;
    return result;
}
napi_value node_stop(napi_env env, napi_callback_info info){
    napi_value result;
    napi_status status;
    int answer = stop();
    status = napi_create_int64(env, answer, &result);
    if (status != napi_ok) return NULL;
    return result;
}
napi_value helloWorld(napi_env env, napi_callback_info info) {
  napi_value world;
  napi_status status;
  const char* str = "world";
  size_t str_len = strlen(str);
  status = napi_create_string_utf8(env, str, str_len, &world);
  if (status != napi_ok) return NULL;
  return world;
}

//module.c
#include "robot_node.h"
#include "node_common.h"

napi_value init(napi_env env, napi_value exports) {
  napi_status status;
  napi_value fn;
  napi_property_descriptor commands[] = {
    DECLARE_NAPI_PROPERTY("hello", helloWorld),
    DECLARE_NAPI_PROPERTY("forward", node_forward),
    DECLARE_NAPI_PROPERTY("stop", node_stop)
  };
  status = napi_define_properties(env, exports, 1, commands);
  if (status != napi_ok) return NULL;
  return exports;
}

//test.mjs
import Bind from 'bindings';

const bindings = Bind("robot-ui.node");
const result = bindings.hello();

console.log(`The result is ${result}`);
bindings.forward();
setTimeout(()=>{
  bindings.stop();
}, 1000);

When I run the hello world part works fine but the forward and stop functions fail with...

TypeError: bindings.forward is not a function

I am pretty new to C development and do not understand how to find the error. Why is the hello world function working fine but the forward function failing?

1

There are 1 best solutions below

0
On

Oops just realized

status = napi_define_properties(env, exports, 1, commands);

Should be

status = napi_define_properties(env, exports, 3, commands);