I've been working on a N-API module by customizing the ObjectWrap boilerplate provided in generator-napi-module. So far, I have successfully passed an array containing objects with string, number, and boolean properties from native C++ code to JavaScript. However, I've encountered an issue when trying to extract a uint32_t value from a number property of one of these objects back in the native code.
Let's say we create an array of objects and pass it to JS:
Napi::Value ObjectWrapAddon::GetSomeList(const Napi::CallbackInfo& info){
Napi::Env env = info.Env();
native_struct_one *data = NULL;
native_struct_two opts = { TRUE,FALSE,FALSE };
int retVal = native_lib_method(&data, &opts);
if(retVal!=OK) {
return Napi::Array::New(env); // return empty array
}
Napi::Array arr = Napi::Array::New(env);
uint32_t i = 0;
do {
Napi::Object tempObj = Napi::Object::New(env);
tempObj.Set("someProp", data->someVal);
arr[i] = tempObj;
i++;
data = data->next;
} while(data);
return arr;
}
And then we pass one of those objects to a native function:
Napi::Value ObjectWrapAddon::OtherMethod(const Napi::CallbackInfo& info){
Napi::Env env = info.Env();
Napi::Object obj = info[0].As<Napi::Object>();
uint32_t temp = obj.Get("someProp").As<Napi::Number>();
return Napi::Number::New(env, temp);
}
While the code compiles without errors, the OtherMethod() function throws an A number was expected
error at
uint32_t temp = obj.Get('someProp').As<Napi::Number>()
.
What is the correct way to extract a native (C++) value from a property of a JS object?