Search code examples
c++node.jsv8

NodeJS Nan C++ bind nested object to addon instance


In a C++ NodeJS project I'm currently working on, I want to have an object which contains a nested object, like

console.log(object.myObject); // { [keys: string]: any }

Without binding objects to properties my addon is working very well. I create the Instance with

auto ctor = Nan::New<v8::FunctionTemplate>(New);
auto ctorInst = ctor->InstanceTemplate();

And bind the object to the class instance like

v8::Local<v8::Object> obj = Nan::New<v8::Object>();
ctorInst->Set(Nan::New("myObject").ToLocalChecked(), obj);

which prints the following when executing the JS code (create an instance of the C++ extension).

# Fatal error in , line 0

# Check failed: !value_obj->IsJSReceiver() || value_obj->IsTemplateInfo().

On the other hand binding primitives (number, string, etc.) works flawlessly.

ctorInst->Set(Nan::New("myObject").ToLocalChecked(), Nan::New<v8::Number>(42));

Do you have got any suggestions? Thanks and cheers!


Solution

  • All templates (Including InstanceTemplate's) can only have other templates, or primitives, in them. As you see, IsTemplateInfo was false, when it should have been true. A similar question was asked and answered here. Simply make an ObjectTemplate and then populate it like you were doing with the FunctionTemplate.

    Only when the Template is instantiated (with GetFunction), can you populate it with real objects.