0

I'm writing a Node.js native add-on (with nan helper module). I want to create and export an ES6 class value, whose type is "function" and .toString() is "class ... { ... }". Viz., I want to know the native equivalent of:

module.exports = class CLASS_NAME {};

.


The only thing I could find on the V8 documentation for doing this, was .SetName().

#include <nan.h>

#define LOCAL_STRING(c_string) (Nan::New(c_string).ToLocalChecked())
#define LOCAL_FUNCTION(c_function) \
    (Nan::New<v8::FunctionTemplate>(c_function)->GetFunction())

void method(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
    info.GetReturnValue().Set(LOCAL_STRING("world"));
}

void initialize_module(
    v8::Local<v8::Object> exports,
    v8::Local<v8::Object> module
)
{
    v8::Local<v8::Function> f = LOCAL_FUNCTION(method);
    f->SetName(LOCAL_STRING("FUNCTION_NAME")); // The only thing I could do
    module->Set(
        LOCAL_STRING("exports"),
        f
    ); // module.exports = f;
}

NODE_MODULE(blahblah, initialize_module)

But it only alters the name of a function:

module.exports = function FUNCTION_NAME { ...... };

, which does not create an ES6 class at all.


How do I do this?

Community
  • 1
  • 1

1 Answers1

0

I think you need to name the function template by calling its SetClassName(v8::String) method.

If your function template is a constructor, it is also a good idea to name its prototype object template by setting symbol getToStringTag like:

prototype_template->Set(
    v8::Symbol::GetToStringTag(isolate),
    v8::String::New(isolate, "prototype_name"),
    static_cast<v8::PropertyAttribute>(...);
hyperandroid
  • 81
  • 1
  • 4