void WAes::Init(v8::Handle<v8::Object> exports) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New(ClassName).ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // methods SetPrototypeMethod(tpl, "encrypt", Encrypt); SetPrototypeMethod(tpl, "decrypt", Decrypt); SetPrototypeMethod(tpl, "encryptGcm", EncryptGcm); SetPrototypeMethod(tpl, "decryptGcm", DecryptGcm); SetPrototypeMethod(tpl, "export", Export); constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); // static methods Nan::SetMethod(tpl->GetFunction(), "generate", Generate); Nan::SetMethod(tpl->GetFunction(), "import", Import); exports->Set(Nan::New(ClassName).ToLocalChecked(), tpl->GetFunction()); }
void HelloObject::Init(v8::Local<v8::Object> target) { // A handlescope is needed so that v8 objects created in the local memory // space (this function in this case) // are cleaned up when the function is done running (and the handlescope is // destroyed) // Fun trivia: forgetting a handlescope is one of the most common causes of // memory leaks in node.js core // https://www.joyent.com/blog/walmart-node-js-memory-leak Nan::HandleScope scope; // This is saying: // "Node, please allocate a new Javascript string object // inside the V8 local memory space, with the value 'HelloObject' " v8::Local<v8::String> whoami = Nan::New("HelloObject").ToLocalChecked(); // Officially create the HelloObject auto fnTp = Nan::New<v8::FunctionTemplate>( HelloObject::New, v8::Local<v8::Value>()); // Passing the HelloObject::New method above fnTp->InstanceTemplate()->SetInternalFieldCount(1); // It's 1 when holding the ObjectWrap itself and nothing else fnTp->SetClassName(whoami); // Passing the Javascript string object above // Add custom methods here. // This is how hello() is exposed as part of HelloObject. // This line is attaching the "hello" method to a JavaScript function // prototype. // "hello" is therefore like a property of the fnTp object // ex: console.log(HelloObject.hello) --> [Function: hello] SetPrototypeMethod(fnTp, "helloMethod", hello); // Create an unique instance of the HelloObject function template, // then set this unique instance to the target const auto fn = Nan::GetFunction(fnTp).ToLocalChecked(); create_once().Reset(fn); // calls the static &HelloObject::create_once method // above. This ensures the instructions in this Init // function are retained in memory even after this // code block ends. Nan::Set(target, whoami, fn); }