Handling JavaScript objects in a C++ node nan addon

854 Views Asked by At

My code is passing a JavaScript object to a function implemented in C++. The C++ code needs to validate the type of each property and supply a default value if either the property is missing or the type is wrong.

The following code seems to work (only showing the integer case) but I'm wondering if there is a more straightforward way to handle this. I'm by no means an expert in this area so all suggestions for improvements are welcome.

int get_integer(
    v8::Local<v8::Object> obj,
    v8::Local<v8::String> prop,
    int default_value = 0) {

    if (Nan::Has(obj, prop).FromMaybe(false)) {
        Nan::MaybeLocal<v8::Value> v = Nan::Get(obj, prop);
        if (!v.IsEmpty()) {
            v8::Local<v8::Value> val = v.ToLocalChecked();
            if (val->IsInt32() || val->IsNumber()) {
                return val->IntegerValue();
            }
        }
    }
    return default_value;
}

It's called by code similar to the following:

v8::Local<v8::Object> obj = info[0]->ToObject();
v8::Local<v8::String> prop = Nan::New<v8::String>("prop").ToLocalChecked();
int x = get_integer(obj, prop);
1

There are 1 best solutions below

1
On

If what you are looking for is a simplification, you should have a look at the new API called N-API, supported by NodeJs.

The code becomes lighter as you never have to touch any v8 object directly. The official documentation is mainly for C, but I recommend that you look into the C++ wrapping. The documentation is not complete, but since you have already used NaN, it is quite similar and you can find some articles on it as well as the examples, under the "node-addon-api" folders for the C++ versions.

A conversion tool exists to convert NaN based code to an N-API one, but since you heavily use v8 constructs I recommend that you redo these parts using only the APIs.