插件可从 C++ 函数中创建并返回新的对象,如以下例子所示。
一个带有 msg 属性的对象被创建并返回,该属性会输出传入 createObject() 的字符串:
// addon.cc#include <node.h>namespace demo {using v8::Context;using v8::FunctionCallbackInfo;using v8::Isolate;using v8::Local;using v8::Object;using v8::String;using v8::Value;void CreateObject(const FunctionCallbackInfo<Value>& args) {Isolate* isolate = args.GetIsolate();Local<Context> context = isolate->GetCurrentContext();Local<Object> obj = Object::New(isolate);obj->Set(context,String::NewFromUtf8(isolate,"msg").ToLocalChecked(),args[0]->ToString(context).ToLocalChecked()).FromJust();args.GetReturnValue().Set(obj);}void Init(Local<Object> exports, Local<Object> module) {NODE_SET_METHOD(module, "exports", CreateObject);}NODE_MODULE(NODE_GYP_MODULE_NAME, Init)} // namespace demo
在 JavaScript 中测试它:
// test.jsconst addon = require('./build/Release/addon');const obj1 = addon('hello');const obj2 = addon('world');console.log(obj1.msg, obj2.msg);// 打印: 'hello world'
