getting arguments in c++ from nodejs

Viewed 730

I'm trying to build nthRoot function in c++ and then embed it in my node js project.

the problem is all the tutorials that are on the web are for an old v8 version and don't work in node 12+

I'm not a c++ programmer

#include <node.h>
#include <iostream>


using namespace v8;
using namespace std;


double NthRoot(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
   int n = args[0]->IntegerValue();
   double degree = args[1]->DoubleValue();

   double result =   std::pow(n, 1.0/degree);

   args.GetReturnValue().Set(result);

}

void Initialize(Local<Object> exports) {
   NODE_SET_METHOD(exports, "nthroot", NthRoot);
}

NODE_MODULE(addon, Initialize);
2 Answers

ended up using napi


#include <napi.h>

Napi::Value NthRoot(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();

  if (info.Length() < 2) {
    Napi::TypeError::New(env, "Wrong number of arguments")
        .ThrowAsJavaScriptException();
    return env.Null();
  }

  if (!info[0].IsNumber() || !info[1].IsNumber()) {
    Napi::TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException();
    return env.Null();
  }

  double arg0 = info[0].As<Napi::Number>().DoubleValue();
  double arg1 = info[1].As<Napi::Number>().DoubleValue();
  Napi::Number num = Napi::Number::New(env, pow(arg0,1.0/arg1));

  return num;
}

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

NODE_API_MODULE(cMath, Init)

Even if using Napi is generally better, that does not answer the original question

I think I found some documentation to do it:

// addon.cc
#include <node.h>

using namespace v8;

void Add(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  if (args.Length() < 2) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong number of arguments")));
    return;
  }

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }

  double value = args[0]->NumberValue() + args[1]->NumberValue();
  Local<Number> num = Number::New(isolate, value);

  args.GetReturnValue().Set(num);
}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(addon, Init)

Where the documentation is here: https://node.readthedocs.io/en/latest/api/addons/

Related