In this article, we complete examples of function factories and object factories through nodejs plugins.
First look at the following node.js code, the my_node_addon plugin we reference needs to be exported
createFunc function and createObject function, and the object returned by the createObject function contains
add and addCallback two addition functions
var addon = require('bindings')('my_node_addon.node');
//函数工厂
var func=addon.createFunc()(1);
console.log('Create Function ret:' ,func);
//对象工厂
var obj = addon.createObject();
//调用对象方法
console.log(obj.add(3, 12))
//调用对象的额回调方法
obj.addCallback(1, 2, (ret) => {
console.log(ret);
});
The plug-in source code main.cpp is as follows
#include <napi.h>
/**
* 加法
* @param info
* @return
*/
Napi::Value Add(const Napi::CallbackInfo &info) {
//获取上下文环境
Napi::Env env = info.Env();
//如果参数少于2
if (info.Length() < 2) {
//js中丢出类型异常
Napi::TypeError::New(env, "Wrong number of argumen